Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 避免无限while循环_C_While Loop_User Input_Infinite Loop - Fatal编程技术网

C 避免无限while循环

C 避免无限while循环,c,while-loop,user-input,infinite-loop,C,While Loop,User Input,Infinite Loop,我被困在一个while loop练习中。只要我只输入整数,这个程序就可以正常工作。然而,如果我输入一个字符、一个符号或一个带小数的实数(甚至是整数,比如1.0),我会得到一个无限循环 int main() { int num; printf("Enter an odd number 1 and 10."); while(1) { printf("\n\nEnter : "); scanf("%d", &num);

我被困在一个while loop练习中。只要我只输入整数,这个程序就可以正常工作。然而,如果我输入一个字符、一个符号或一个带小数的实数(甚至是整数,比如1.0),我会得到一个无限循环

int main() 
{
    int num;
    printf("Enter an odd number 1 and 10.");
    while(1) 
       {
        printf("\n\nEnter : ");
        scanf("%d", &num);

        if(num == 0)
            break;
        else if(num < 0 || num > 10)
            printf("You entered number is beyond the range.");
        else if(num % 2 == 0)
            printf("You entered an even number.");
        else
            printf("You entered a correct number.");
       }

   printf("You are exiting the program.");      
   return 0;
} 
intmain()
{
int-num;
printf(“输入奇数1和10”);
而(1)
{
printf(“\n\n输入:”);
scanf(“%d”和&num);
如果(num==0)
打破
否则如果(num<0 | | num>10)
printf(“您输入的数字超出范围。”);
else if(num%2==0)
printf(“您输入了一个偶数。”);
其他的
printf(“您输入了正确的数字。”);
}
printf(“您正在退出程序。”);
返回0;
} 
但是,如果我输入一个字符、符号或带小数的实数?然后您有未定义的行为作为
scanf()
需要
int
参数,但您提供的不是
int
参数

偶数整数,如
1.0
?不,
1.0
不是整数是实数

检查
scanf()
的返回值以了解它是成功还是失败。打开
man 3扫描
并进行分析。例如

int-ret=0

ret=scanf(“%d”和&num)

if(ret!=1){
/*错误处理*/

}

检查扫描结果。
num
如果输入不正确,则不会更改。@Fabio\u MO有条件中断!!我感谢你的帮助。你的方法很简单,但效果很好。再次感谢!