它工作正常,直到你输入一个字符,然后它变成一个无限循环,而不是只是说“无效数字”。我不明白为什么。请帮忙?
#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");
}
}
}
有几个建议可以改进您的代码:
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到23.输入字符时得到的值会在int变量宽度中产生一些非常糟糕的值。为什么?因为scanf函数将输入作为十进制数,所以它读取的不仅仅是一个字符,而且内存中的任何内容都被选为数字。我希望他的帮助。这是一个常见的问题,请在这里查看scanf的用法:http://www.cplusplus.com/reference/cstdio/scanf/