if / else语句只能按整数使用。

问题描述 投票:0回答:2

它工作正常,直到你输入一个字符,然后它变成一个无限循环,而不是只是说“无效数字”。我不明白为什么。请帮忙?

#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");
}
}
}
c scanf
2个回答
3
投票

有几个建议可以改进您的代码:

  • 始终检查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
        }
    }
}

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.