下面的程序就是一个猜数字的游戏,在0-100间的数字,内定一个数字, 然后猜数字,通过交互输入 ,程序最终通过二分法找到我们需要的正确数字。
下面的程序问题应该不是很大, 问题是 每次 只循环7次 ,也就是 输入的次数 达到7次之后,程序就停在那里了 没反应了。
程序如下:
#include<stdio.h>
int center(int start,int end);
int main(void)
{
int guess,start=0,end=100,a,x;
char judge;
printf("Please guess a integer which is between 0 and 100,after i guess ,\n "
"please enter 'y' or 'w' which means right or wrong. if i guess bigger than\n"
"the true value,please enter 'b', if samller ,enter 's'.\n");
printf("Now i start guess, i guess the integer is:\n");
scanf("%d",&guess);
fflush(stdin);
while (guess<0||guess>100)
{
printf("You enter wrong integer which is should between 0 and 100, please enter again:\n");
scanf("%d",&guess);
fflush(stdin);
}
printf("The integer i guess is %d.\n",guess);
printf("Please determine if my guess is equal to the true value,and corresponding to the input 'y' 'b' 's'.\n");
judge=getchar();
getchar();
if(judge=='y')
printf("You are right, your guess is %d which is equal to the true value.\n",guess);
while(judge!='y')
{
switch(judge)
{
case 'b': a=guess;
guess=center(start,guess);
printf("The integer i guess is %d.\n",guess);
printf("Please determine if my guess is equal to the true value,and corresponding to the input 'y' 'b' 's'.\n");
judge=getchar();
getchar();
if (judge=='s')
{
end=a;
}
break;
case 's': x=guess;
guess=center(guess,end);
printf("The integer i guess is %d.\n",guess);
printf("Please determine if my guess is equal to the true value,and corresponding to the input 'y' 'b' 's'.\n");
judge=getchar();
getchar();
if(judge=='b') start=x;
break;
default: break;
}
}
printf("You are right, your guess is %d which is equal to the true value.\n",guess);
return 0;
}
int center(int start,int end)
{
int result1;
result1=(start+end)/2;
return result1;
}
例如 我们假定 真实的数字是 38, 初次输入猜测的数字是 52,
运行的结果如下图:
请问这是什么原因呢?