/*
本程序应题目而建立。
题目要求: 修改程序清单中的 8.4 猜数字程序。 详见数 226 页。
让程序使用更智能的猜测策略。使用 二分查找 策略。
*/
#include<stdio.h>
#include<ctype.h>
#define MAX 100
int main(void)
{
int count = 50; // 保存程序计算结果。程序输出的 初始值 是 55 。
int input = 0; // 接收用户输入。
int i = 0; // 计算用。
int j = 0; // 计算用。
// 旁白部分 。
printf("Welcome to this small program . Now we are playing a game . I wish you can enjoy in it .\n");
printf("The rule is that : The program will guess your imagine number and output that number to show you .\n");
printf("If number is bigger than your imagine , please enter 'big' or 'b' to tell program . \n"
“And it will guess again for another number to show you .\n");
printf("If number is smaller than your imagine , please enter 'small' or 's' to tell program . \n"
"And it will guess again for another number to show you .\n");
/*——————————————————————————————————分割线,太长了 !—————————————————————————————————————————————————*/printf("If I am right , please input 'right' . And program will close .\n");
printf("If you are tirred and Don't wan t to play this game . You are just enter 'q' to quit program .\n");
printf("Game start ! The program will show you the number for your imagine now !\n");
/*——————————————————————————————————分割线,太长了 !—————————————————————————————————————————————————*/
printf("I guess the number is 50 ! Am I right ? Please input :");
input = getchar();
getchar(); //读取换行符。避免程序读取多余字符而引发错误。
while ( input != 'q' )
{
if (input == 's' )
{
// Smaller , 小于用户猜测数字的情况下。
j = count ;
i = MAX - count ;
count += (int) i / 2 ;
printf("\nOk , I guess again ! The number is %d .Am I right ? Please input :", count );
}
else if (input == 'b' )
{
// Bigger , 大于用户猜测数字的情况下。
count = (int) (count - j ) / 2 + j ;
printf("\nOk , I guess again ! The number is %d .Am I right ? Please input :", count );
}
else if (input == 'r' )
{
// Right , 等于用户猜测数字的情况下。
printf("\nAlright , I guess right at last !\n");
break;
}
else
{ //莫名情况。
printf("\nWORRING ! This program is failed to run ! And it will close for now ! \n");
break;
}
input = getchar();
getchar(); //读取换行符。避免程序读取多余字符而引发错误。
}
printf("Game is over ! Welcome to here next time ! \n");
printf("Bye !\n");
//暂停页面专用。
getchar();
getchar();
return 0;
}