/*修改程序清单8.4的猜数字程序,使用更智能的猜测策略。例如,程序最初猜50,询问用户是猜大了、猜小了还是猜对了。
如果猜小了,那么下一次猜测的值应是50和100中值,也就是75。如果这次猜大了,那么下一次猜测的值应是50和75的中值,等等。
使用二分查找(binarysearch)策略,如果用户没有欺骗程序,那么程序很快就会猜到正确的答案。
#include<stdio.h>
int main(void)
{
int guess = 1;
printf("Pick an integer from 1 to 100. I will try to guess");
printf("it.\nRespond with a y if my guess is right and with");
printf("\nan n if it is wrong.\n");
printf("Uh... is your number %d?\n",guess);
while(getchar()!='y')
printf("Well,then,is it %d\n",++guess);
printf("I knew I could do it!\n");
return 0;
}
*/#include<stdio.h>intmain(void){int guess;int max =100;int min =1;int mid = max /2;char ch;printf("Pick an integer from 1 to 100. I will try to guess.\n");scanf("%d",&guess);printf("Respond with b(big) or s(small), respond y if my guess is right ");printf("Uh... is your number %d?\n", mid);while((ch =getchar())!='y'){if(ch =='\n')continue;if(ch =='b'){
max = mid;
mid =(max - min)/2+ min;printf("Well,then,is it %d\n", mid);printf("guess=%d\n", guess);}elseif(ch =='s'){
min = mid;
mid =(max - min)/2+ min;printf("Well,then,is it %d\n", mid);printf("guess=%d\n", guess);}}return0;}