#include"stdio.h"
#include"stdlib.h"
void main()
{
int guess=0,problem,ch;
ch=getchar();
do
{scanf("%d",&guess);
problem=(int)(rand()%100)+1;
for(;guess!=problem;)
{if(guess>problem)
printf("too high!");
if(guess<problem)
printf("too low!");
scanf("%d",&guess);
}
printf("%d",problem);
ch=getchar();
}while(ch!='n');
}为什么猜完一次数字后,我按任意键程序都会进入死循环!!

c 语言的问题求大神的指导!
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
3条回答 默认 最新
- save4me 2015-07-15 03:52关注
你的代码问题在于scanf没有判断输入的是否是数字,如果不是数字,就会进入死循环。加一个判断就好了。
不过你也可以使用fgets之类的替代scanf,方便指定输入数据类型。#include <stdio.h> #include <stdlib.h> void main() { int guess = 0, problem; char ch = getchar(); int isNumber; do { isNumber = scanf("%d", &guess); if(isNumber == 0) { printf("please input a number!"); ch = getchar(); continue; } problem = (int)(rand() % 100) + 1; for(; guess != problem;) { if(guess > problem) printf("too high!"); if(guess < problem) printf("too low!"); scanf("%d", &guess); } printf("%d", problem); ch = getchar(); }while(ch != 'n'); }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报