【发布时间】:2019-10-07 07:41:33
【问题描述】:
程序会不断地将数字扫描到一个数组中,其中数组的值不会超过 100 个。
但是,尽管程序在输入第三个值后退出,但第一个 while 循环中的计数器“i”继续计数到 99。因此,当启动第二个 while 循环时,它会打印从 99 开始的值。
如何在退出循环时让计数器停止?
这是一个家庭作业,也是第一次接触 C 中的数组。
我已经尝试使用 if 语句来排除所有不必要的数组值的零,但有时可以将 0 输入到数组中并需要打印。
#include <stdio.h>
int main(void) {
printf("Enter numbers forwards:\n");
int numbers[99] = {0};
// Components of the scanning while loop
int i = 0;
while (i <= 98) {
scanf("%d", &numbers[i]);
i = i + 1;
}
// Components of while loop
int counter = i - 1;
printf("Reversed:\n");
while (counter >= 0) {
printf("%d\n", numbers[counter]);
counter--;
/*if (numbers[counter] == 0) {
counter--;
} else {
printf("%d\n", numbers[counter]);
counter--;
}*/
}
预期结果: 输入号码转发: 10 20 30 40 50 CTRL-D 反转: 50 40 30 20 10
实际结果: 输入号码转发: 10 20 30 40 50 CTRL-D 反转: 0 0 0 ... 50 40 30 20 10
【问题讨论】:
-
提示:看看
scanf的返回值,看看你是否可以改变你的第一个while循环的条件来利用它。 -
调用
scanf时,总是检查它的返回值。如果您尝试匹配一个输入,而scanf没有报告它已匹配 1 个输入,则出现问题。