【发布时间】:2013-12-03 15:32:30
【问题描述】:
我是 C 新手,今天遇到了一个我还没有弄清楚的问题,所以我需要一些帮助。我们被赋予了这个任务:
'编写一个程序来演示一个使用“预读”技术的“while”循环:它要求用户输入 10 和 100 之间(包括)10 和 100 之间的数字,输入零会终止循环。如果输入小于 10 或大于 100 的数字,则会显示错误消息(例如“错误:不允许 250”)。循环终止后,程序会打印输入的数字数量。'
我遇到的问题是,一旦我输入了一个有效数字(10-100 之间),程序就会静止不动,它既不会终止也不会循环。另一方面,如果我输入一个无效的数字,比如 8, 102,它会循环 printf("Error, %d is not allowed\n", num);
代码如下:
#include <stdio.h>
main(void)
{
int num;
int counter=1;
printf("Please type in your number between (and including) 10-100\n");
scanf("%d", &num);
if((num <10) || (num >100))
{
printf("Error, %d is not allowed\n", num);
}
while (num > 0)
{
counter++;
if((num <10) || (num >100))
{
printf("Error, %d is not allowed\n", num);
}
counter++;
}
printf("%d numbers were entered!\n", counter);
}
【问题讨论】:
-
您需要 scanf(...) 循环的每次迭代来获取一个新数字。
标签: c loops while-loop