繁体   English   中英

Scanf 函数不会遍历我的 while 循环

[英]Scanf function will not loop through my while loop

    k = 0;
    while (k == 0){
        printf ("enter a value between 0 - 80\n");
        scanf ("%d", &coldest);

        if(coldest <= 80 && coldest >= 0){
            k = 1;
        }
        else 
            k = 0;
    }
    printf ("this number ---->%d<-----\n", coldest);

这就是我写的,当你在参数 0-80 之外放入任何东西时,它应该循环并再次询问用户,但我遇到了一个问题,它会跳过scanf并继续弹出printf

编辑:≤ to <= and ≥ to >= -Edit2: 80 <= 最冷到最冷 <= 80

if条件测试

is coldest >= 80
AND
is coldest >= 0

你现在能发现错误吗?

此外,不测试来自scanf的返回值总是一个错误

修改if条件为

if(coldest <= 80 && coldest >= 0)

如果上述条件为真,则表示输入的值在指定范围内..

        int main() {
        int coldest = 0;
        int k = 0;
        while (1){ /* while(1) so that until input is not correct keep on ask */

                printf ("enter a value between 0 - 80\n");
                scanf ("%d", &coldest);

                /* if this condition is true means no need to ask user again for input so use break to come out from loop */
                if(coldest <= 80 && coldest >= 0) {
                        k = 1;
                        break;
                }
                else { 
                        k = 0;
                        printf ("not in the range [%d]\n", coldest);
                }
        }
        printf ("this number ---->%d<-----\n", coldest); /* once loop fails it prints */
        return 0;
}

在您的代码中if(80 <= coldest && coldest >= 0) if在检查条件后执行。 在您的代码中有两个条件80 <= coldestcoldest >= 0 它们由&&运算符连接。

您要检查给定的输入是否在 0 到 80 的范围内。首先检查coldest是否大于或等于 80,同时检查coldest是否大于 0。这是由于使用&& . 您要检查以下情况:-

  1. coldest大于 80
      && 或者,
  2. coldest小于 0

只需将if(80 <= coldest && coldest >= 0)的条件更改为if(coldest >= 80 || coldest <= 0) 您的代码中存在逻辑错误。 只将&&改为|| . 示例:- 如果coldest = 90; 比最冷的是

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM