下面的提示是在我的计算机科学课程期末介绍上。
按照下面的描述编写一个程序:用户挑选数字,告诉计算机它的猜测是太高还是太低,直到计算机猜对为止。 如果操作正确,程序应该能够在7次猜测内确定数字(假设人类没有作弊)。 (提示:二分搜索--在可能的数字之间的一半进行搜索)。 为您的程序提供测试值和预期结果。
下面是我得到的代码。 在此之前,我创建了一个反向程序,其中计算机生成一个随机数,用户进行猜测,我也见过其他人的程序,其中给出了计算机应从中选择的一个数字范围(例如1-100)。 但是我不知道该怎么做,我的老师也没有给我一个答案。
我们也没有学到什么是二分搜索,也没有学到如何使用它。
#include <iostream>
int main()
{
cout<< "Choose a number :";
int a;// create variable A
cin>>a;//User inputs number
int b;
//computer produces random number and stores in variable b (need code)
While (a != b)//compare variable to a to b
{
cout<<"Is "<<b<<" too high? (enter y for yes or n for no) : ";
char c;//char size variable created called c
cin>>c;//User input (y or n) overwrites c
bool d;//bool size variable created called d
if (c==y)
{
d=true;
}
else
{
d=false;
}
if (d)
{
//b reduced and overwrites b (need code)
}
else
{
//b enlarged and overwrites b (need code)
}
cout<< "Computer guesses : "<<b;
}
cout<< "Your number is "<<b;
}
你应该试着从计算机的角度思考,因为计算机不知道答案。
当你从玩家那里得到答案时,你(计算机)就获得了信息。 信息是未知数所处的范围。 即最小值和最大值。 将其初始化为(0,100)。 每次从播放机获得答案时更新此内容。 重复,直到最小值=最大值。
当心一个错误。