C++ 计算机猜测用户数量在 7 次猜测以内

C++ Computer guesses users number within 7 guesses

本文关键字:计算机 用户数 C++      更新时间:2023-10-16

以下提示出现在我的计算机科学课程决赛介绍中。

根据以下描述编写程序: 用户选择数字并告诉计算机它的猜测是太高还是太低,直到计算机猜对为止。 如果操作正确,程序应该能够在7次猜测中确定数字(假设人类没有作弊(。 (提示:二叉搜索 - 尝试在可能的数字之间(。 为程序提供测试值和预期结果。

如何让它在7 次尝试内猜测?

#include <time.h>
#include <iostream>
using namespace std;
int main()
{ 
int min,max;
cout<<"To begin guessing game, enter maximum and minimum game parameters (positive integers).n";
cout<<"Enter minimum value : ";
cin>>min;
cout<<"Enter maximum value : ";
cin>>max;
cout<< "Choose a number between "<<min<< " and "<<max<<" : ";
int userNum;// create variable A
cin>>userNum;//User inputs number 
int compGuess;
srand(time(NULL));
compGuess = rand() % max + min;//computer produces random number between 1 and 100 and stores in variable b

while (userNum != compGuess)//compare variable to a to b
{
cout<<"Computer guesses "<<compGuess;
cout<<endl;
cout<<"Is your number higher? (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;
min=compGuess;
}
else  
{
d=false;
max=compGuess;
}

if (d)
{
compGuess=(compGuess+max)/2;
}
else
{
compGuess=(min+compGuess)/2;  
}
}   
cout<< "Your number is "<<compGuess;   

}        






















你应该试着从不知道答案的计算机的角度思考。

当你从玩家那里得到答案时,你(计算机(会获得信息。该信息是未知号码所在的范围。也就是说,最小值和最大值。将其初始化为 (0, 100(。每次从玩家那里得到答案时都会更新它。重复直到最小值 = 最大值。

当心逐一错误。

相关文章: