# 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;
}
}
修改程序清单8.4的猜测程序,使其使用更智能的猜测策略。例如,程序最初猜50,让其询问用户该猜测值是大、小还是正式。如果该猜测值小,则令其下一次猜测值为50和100的中值,也就是75,。如果75大,则下一次猜测为75和50的中值,等等。使用这种二分搜索策略,起码如果用户没有欺骗,该程序很快会获得正确答案。解:原题目是猜测1~100中的数字。# include <stdio.h># include