我是 C 新手,今天遇到了一个我没有弄清楚的问题,所以我需要一些帮助。我们被赋予了这个任务:
'编写一个程序,演示使用“预读”技术的“while”循环:它要求用户输入 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);
}
最佳答案
您必须在循环内询问一个数字:
printf("Please type in your number between (and including) 10-100\n");
scanf("%d", &num);
请检查 scanf
的返回码以检测错误。
最后,您在循环内将计数器增加两次。
关于C:我的循环似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20082420/