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

时间:2018-02-25 14:40:45

标签: c

    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

编辑:≤到&lt; =和≥到&gt; = -Edit2:80&lt; =最冷到最冷&lt; = 80

3 个答案:

答案 0 :(得分:1)

if条件测试

is coldest >= 80
AND
is coldest >= 0

你现在可以发现错误吗?

此外,不测试scanf的返回值始终是错误

答案 1 :(得分:0)

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;
}

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

(*keys, k)

答案 2 :(得分:0)

在您的代码if(80 <= coldest && coldest >= 0)中。检查条件后执行if。在您的代码中,有两个条件80 <= coldestcoldest >= 0。他们由&&运营商加入。

您想要检查给定输入是否在0到80的范围内。首先检查coldest是否大于或等于80,此时它还会检查coldest是否更大由于&&的使用而产生。您想检查以下情况: -

  1. coldest大于80
              && or,
  2. coldest小于0
  3. 只需将if(80 <= coldest &amp;&amp; coldest >= 0)的条件更改为if(coldest >= 80 || coldest <= 0)。您的代码中存在逻辑错误。只需将&amp;&amp; 更改为 || 。例:- 如果coldest = 90;比最冷的话