gpt4 book ai didi

c - 避免无限 while 循环

转载 作者:行者123 更新时间:2023-11-30 16:31:16 24 4
gpt4 key购买 nike

我陷入了 while 循环练习。只要我只输入整数,该程序似乎就可以正常工作。但是,如果我输入字符、符号或带小数的实数(甚至是 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;
}

最佳答案

但是,如果我输入一个字符、符号或带小数的实数?那么你就会有未定义的行为,如scanf()需要 int 参数,但您提供的不是 int 参数。

甚至是1.0这样的整数?不,1.0不是整数,它是一个实数。

检查scanf()的返回值来判断是否成功。打开 man 3 scanf 并分析。例如

int ret = 0;

ret = scanf("%d",&num);

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

关于c - 避免无限 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50720497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com