# include <stdio.h># include <ctype.h>int mean(int, int); //输值取中值void clear(void); //清除取值以外的字符bool is_effective(int); //判断要猜的整数是否有效int get_in(void); //取的要猜的整数int main(void)
{
constint MIN = 1; //下限constint MAX = 100;
intin;
char ch;
int low = 1;
int high = 100;
int cnt = 0; //计数 用于判断是否是第一次判断
printf("Please enter a integer,1 to 100 .\n");
printf("You can choice L, h or y.\n");
printf("L is low, h is high,y is yes.such as 20<50 is L, 20 is your number.\n");
in = get_in();
clear();
printf("50 is yes?\n");
while(tolower((ch = getchar())) != 'y')
{
if(ch == 'l' || ch == 'h')
{
if(cnt == 0)
in = 50;
switch(ch)
{
case'l':
high = in;
in = mean(low, high);printf("%d is your number?\n",in);
break;
case'h':
low = in;
in = mean(low, high);printf("%d is your number?\n",in);
break;
}
}
else
{
printf("error!\nyou can choice l, h, y.OK!\n");
}
cnt++;
}
printf("your number is %d\n", in);
return0;
}
int mean(int low, int high)
{
intin;
in = (high + low) / 2;
clear();
returnin;
}
void clear(void)
{
while(getchar() != '\n')
continue;
}
bool is_effective(intin)
{
if(in <= 100 || in >= 1)
returntrue;
elsereturnfalse;
}
int get_in(void)
{
intin;
if(is_effective(in))
{
returnin;
}
else
{
printf("Enter a integer :\n");
scanf("%d", &in);
returnin;
}
}