修改程序清单8.4中的猜测程序,使其使用更加智能的猜测策略,例如,程序最初猜50,让其询问
用户该猜大,小还是正确。如果该猜值小,则令下一次猜测值为50和100值,也就是75,如果75大,
则下一次猜测75与50之间的值等等,使用这种二分搜索策略,起码如果用户没有欺骗,该程序很快
会获得正确答案。
/*#include <stdio.h>
#include <windows.h>
int main(void)
{
int guess = 50;
int gue = 50;
char xz;
printf("Pick an integer from 1 to 100. I will try to guess it.\n");
printf("Respond with a y if my guess is right and with an n if it is wrong.\n");
printf("Uh...is your number %d?\n", guess);
while ((xz = getchar()) != 'y') {
switch (xz) {
case 'd':gue = (0 + gue) / 2;
printf("%d\n", gue);
break;
case 'x':gue = (gue + 100) / 2;
printf("%d\n", gue);
break;
default: break;
}
}
printf("I knew I could do it!\n");
system("pause");
return 0;
}*/
以上程序还是有瑕疵。。
#include <stdio.h>
#include <windows.h>
int main(void)
{
int low, high, mid;
low = 1, high = 100, mid = 50;
char xz;
printf("Pick an integer from 1 to 100. I will try to guess it.\n");
printf("Respond with a y if my guess is right and with an n if it is wrong.\n");
printf("输入'q'退出,请输入'd'表明此数太大了,或'x'表明此数太小了: \n");
printf("Uh...is your number %d?\n", mid);
while ((xz = getchar()) != 'q' && low < high) {
if(xz == 'y'){
printf("正确!\n");
}else if (xz == 'd') {
printf("太大了吧!\n");
high = mid - 1;
}else if(xz == 'x') {
printf("太小了吧!\n");
low = mid + 1;
}
mid = (high + low) / 2;
printf("是%d吗,太大输入d,太小输入x,正确输入y。\n", mid);
while ((xz = getchar()) != '\n') {
continue;
}
}
printf("I knew I could do it!\n");
system("pause");
return 0;
}