有谁知道这段代码有什么问题?即使在输入> 1行之后,程序也会在代码结束时提前结束,而不允许嵌套while重复。谢谢。
#include <stdio.h>
int main() {
int line;
unsigned int sum = 0;
int input;
float average;
printf("Enter number of input lines:");
scanf("%d", & line);
while (line > 0) {
while (input != -1) {
printf("Enter input line:");
scanf("%d", & input);
sum += input;
printf("sum is %d", sum);
printf("Line is %d", line);
}
line--;
printf("Line is %d", line);
}
return 0;
}
答案 0 :(得分:1)
在你的程序中,内循环条件基于变量input
。但是在退出内循环之前,它的值在内循环内设置为-1
。但变量input
的值一旦变为-1
就不会改变。
修改如下以在外循环的每次迭代中输入内循环
printf("Enter number of input lines:");
scanf("%d",&line);
while (line>0) {
input = 0; /* This line is additional */
while (input != -1) {
printf("Enter input line:");
scanf("%d",&input);
sum += input;
printf("sum is %d",sum);
printf("Line is %d",line);
}
line--;
printf("Line is %d",line);
}