#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');
}为什么猜完一次数字后,我按任意键程序都会进入死循环!!
你的代码问题在于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');
}
把类型都定义对了,你这里ch应该是char,别定义成int
while(ch!='n');
按n退出。