我目前在大学的C语言班。我总是喜欢把交给我的任务编程得方便、整洁。所以,请记住,我是初学者。
虽然这是基本的,但我只是需要帮助:
1 int count, sum, max, input;
2 count = 1;
3 sum = 0;
4 input = 0;
5 printf("This program will find the sum of your given
6 input of an integer.n");
7 printf("Please enter the number you would like the sum
8 of: ");
9 scanf("%d", &max, &input);
10 while (count <= max){
11 sum = sum + count;
12 count++;
13 }
14 printf("The sum of %d is %d.n", input, sum);
15 printf("==To exit the program, please enter anything,
16 then press enter==");
17 scanf("%d");
18 return;
}
我想让用户在第14行知道他们首先输入了什么,同时也给他们输入的总和。我该怎么做呢?
编辑:我知道第9行没有意义,但这就是我遇到问题的地方。我已经见过scanf("%d%d", &var, &var);,但这需要用户有两个输入。我只需要一个输入。换句话说,如果用户输入一个数字,我希望只有一个输入可以同时进入max
和input
。
编辑2:例如,如果您输入想要获得10
的总和,我希望第14行显示您输入的输入以及显示10
的总和。
scanf()
将只分配给格式字符串中有多少个格式操作符的变量。您提供的额外变量将被忽略,它不会获得相同输入值的副本。
使用普通赋值将输入的值复制到第二个变量中。
scanf("%d", &max);
input = max;
我认为你不需要声明一个额外的变量' input ';(因为max的值在你的代码中永远不会改变。)
检查下面的代码:
1 int count, sum, max; //removed input
2 count = 1;
3 sum = 0;
4 //removed input
5 printf("This program will find the sum of your given
6 input of an integer.n");
7 printf("Please enter the number you would like the sum
8 of: ");
9 scanf("%d", &max);
10 while (count <= max){
11 sum = sum + count;
12 count++;
13 }
14 printf("The sum of %d is %d.n", max, sum); //replaced input by max
15 printf("==To exit the program, please enter anything,
16 then press enter==");
17 scanf("%d");
18 return;
}