代码之家  ›  专栏  ›  技术社区  ›  Adam Grey

If/else语句仅适用于整数。

  •  0
  • Adam Grey  · 技术社区  · 7 年前

    它工作得很好,直到您输入一个字符,然后它就变成了一个无限循环,而不仅仅是说“无效数字”。我不明白为什么。请帮忙?

    #include <stdio.h>
    int main (void)
    {
    int i = 0;
    int number;
    while (i == 0){
            printf("Enter a number greater than 0 and smaller than 23.\n");
            scanf (" %d", &number);
            if (number < 23 && number > 0 ){
                printf("Sucess!\n");
                break;
            } else {
                printf("Invalid number.\n");
    }
    }
    }
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   Weather Vane    7 年前

    有几种改进代码的建议:

    • 始终检查返回值 scanf ,告诉你有多少 已成功读取输入。
    • 未处理的输入保留在输入缓冲区中,必须清除 出来
    • 未初始化的变量可能会误导您。
    • 利用 i 控制循环的变量。

    修改意见:

    #include <stdio.h>
    
    int main (void)
    {
        int i = 0;
        int number = 0;                                 // an invalid value
        while (i == 0) {
            printf("Enter a number greater than 0 and smaller than 23.\n");
            if(scanf("%d", &number) == 1 && number < 23 && number > 0 ) {
                printf("Success!\n");
                i = 1;                                  // satisfy the loop control
            } else {
                printf("Invalid number.\n");
                while(getchar() != '\n');               // clear the input buffer
            }
        }
    }
    
        2
  •  0
  •   VladP    7 年前

    简单地说,输入的值超出了检查范围0到23。输入字符时得到的结果在int变量width中放入了一些非常糟糕的值。为什么?因为scanf函数将输入作为十进制数,所以它读取的不仅仅是一个字符,内存中的任何内容都会被选为一个数字。我希望他的帮助。 这是一个常见问题,请在此处查看scanf的用法: http://www.cplusplus.com/reference/cstdio/scanf/