我正在尝试将数字列表作为字符串读取,并计算应该有多少个包装。每个包的最大值为50。例如,"20 25 25 39 37 25 20 10 50 8 16 45 32 10 25 -1"
的输出应为11,但我得到10。
您能不能查看我的代码?
int main(void) {
int input = 0;
int temp = 0;
int diff = 50;
int output = 0;
printf("Input: \n");
do {
scanf("%d", &input);
if (input < diff) {
diff -= input;
} else if (diff == 0 || diff == input) {
diff = 50;
output++;
} else {
diff = 50 - input;
output++;
}
} while (input != -1);
printf("Output: %d", output);
return 0;
}
正如我在注释中提到的,您在循环的开始读入input
一次,并在循环的结束将其与-1
进行比较,因此-1
将得到处理与每个其他input
值相同。
最明显的选择是在两个不同的地方读取,一次在循环之前,一次在循环结束时,这样,您将获得一个新的input
值直接在]之前>循环条件:] >printf("Input: \n");
scanf("%d", &input);
while(input != -1) {
// Processing
scanf("%d", &input);
}
注意,我还将循环切换到while
循环而不是do ... while
循环,就像提供的输入[[only
-1
一样,然后do ... while
仍会处理它,从而导致错误的输出。