C:我的循环似乎不起作用

标签 c loops while-loop

我是 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/

相关文章:

使用 SWIG 从 Ruby 调用 C 回调

javascript for 循环顺序

java - 真假游戏在第一轮后不起作用

c# - while 循环不会在 false 条件下退出

javascript - 求两个值的公因数

c++ - 如何调用用c++编写的程序调用我用c编写的DLL

c - 在 C/C++ 中求值和替换

python - 根据值以特定顺序遍历 numpy 数组

java - try catch 异常无限 while 循环

c - 如何在函数中传递结构体数组并在 C 中更改其参数