C++ 计算机猜测用户数量在 7 次猜测以内
C++ Computer guesses users number within 7 guesses
以下提示出现在我的计算机科学课程决赛介绍中。
根据以下描述编写程序: 用户选择数字并告诉计算机它的猜测是太高还是太低,直到计算机猜对为止。 如果操作正确,程序应该能够在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(。每次从玩家那里得到答案时都会更新它。重复直到最小值 = 最大值。
当心逐一错误。
相关文章:
- 为什么使用 P/Invoke 调用 dll 时,某些计算机中的 LoadLibrary 失败?
- EvtExportLogneneneba API正在将远程计算机的事件日志保存到远程PC本身.如何将其保存到主机
- 为什么我能够为阵列分配比计算机实际拥有的内存更多的内存
- 我可以使用任何好的逻辑来阻止计算机将 O 放在井字游戏中的现有 X 上
- C++ 计算机猜测用户数量在 7 次猜测以内
- C++为什么我的编译器成功了,但我的计算机给出了调试错误?
- 在 c++ 中连接字符串和整数,以便在 C++ 11 不支持计算机的情况下读取多个文件
- 我的 SDL2 程序需要哪些二进制文件,以便它在另一台未安装 SDL2 的计算机中工作
- 将非常大的 int 转换为双倍,在某些计算机上会损失精度
- 如何在个人计算机和群集 (c++) 上生成相同的随机数
- 系统错误:程序无法启动,因为您的计算机中缺少MSVCP140D.DLL。尝试重新安装该程序以解决此问题
- 预处理的 C/C++ 文件是否特定于计算机?
- Windows桌面程序保存您的计算机会话 - 基于程序崩溃时的恢复会话
- 我会导致太多内存泄漏,以至于我的计算机无响应吗?
- 在多 GPU 计算机中查找空闲 GPU
- 我该如何编码,使计算机知道两个名称条目和三个名称条目之间的区别
- 从C++中的主机名获取计算机名
- 我的C++程序如何访问计算机的日期和时间以打印和使用当前年份?
- 如何使Visual Studio 2017 C++项目在计算机之间更具可移植性
- 计算机使用什么方法添加无符号整数