c++ - 电脑猜你的号码
问题描述
我需要制作一个“猜谜游戏”,但我被困住了,因为我不确定这是否是正确的制作方法,因为在玩游戏时很难找到我正在考虑的数字。
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int guess;
int n=500;
cout<<"Think of a number from 1 to 1000."<<endl;
cout<<"The number is : 1. 500"<<endl;
cout<<"2. Bigger than 500"<<endl;
cout<<"3. Smaller than 500"<<endl;
cin>>guess;
while(n<=2000)
{
if(guess==1)
{
cout<<"The computer has guessed the number!";
break;
}
else if(guess==2)
{
n+=n/2;
cout<<"The number is :\n1."<<n<<endl;
cout<<"2. Bigger than "<<n<<endl;
cout<<"3. Smaller than "<<n<<endl;
cin>>guess;
}
else if(guess==3)
{
n-=n/2;
cout<<"The number is :\n1."<<n<<endl;
cout<<"2. Bigger than "<<n<<endl;
cout<<"3. Smaller than "<<n<<endl;
cin>>guess;
}
}
}
我似乎找不到更好的方法来制作游戏。这个数字总是超过,1000
所以我不得不将它设置while
为低于2000
它才能工作。
如果我可以设置n+=n/2
公式以便拆分作为n
变量的最后一个数字,那就太好了。例如 : 500+(500/2)
, then 750+(250/2)
, then 875+(125/2)
(不确定当125
拆分为时它会如何继续62.5
)或与n-=n/2
.
解决方案
#include <iostream>
using namespace std;
int main()
{
int guess;
int min = 0, current = 500, max = 1000;
cout << "Think of a number from 1 to 1000." << endl;
cout << "The number is : 1. 500" << endl;
cout << "2. Bigger than 500" << endl;
cout << "3. Smaller than 500" << endl;
cin >> guess;
while (current <= 2000)
{
if (guess == 1)
{
cout << "The computer has guessed the number!";
break;
}
else if (guess == 2)
{
min = current;
current = (min + max) / 2;
cout << "The number is :\n." << current << endl;
cout << "2. Bigger than " << current << endl;
cout << "3. Smaller than " << current << endl;
cin >> guess;
}
else if (guess == 3)
{
max = current;
current = (min + max) / 2;
cout << "The number is :\n." << current << endl;
cout << "2. Bigger than " << current << endl;
cout << "3. Smaller than " << current << endl;
cin >> guess;
}
}
}
这应该有效。并在每次猜测后有效地限制域min
。max
推荐阅读
- mysql - 如何在 SQLAlchemy 中为所有表全局设置“mysql_default_charset”和“mysql_collate”,而不是使用“__table_args__”在每个表的基础上设置?
- google-api - 谷歌 javascript api 客户端,自动登录同一个帐户而不弹出
- node.js - 安装 node.js、npm 和无服务器时出错
- azure-data-factory - Azure 数据工厂 - 复制并行度
- sql-server - Acumatica:自定义表架构在发布时导致错误
- python - 正则表达式花费太多时间
- python - 对 groupby 对象执行更复杂的计算
- python - 如何在 Digital Micrograph 中的 dm-script 和 python 之间进行通信
- react-native - 根据状态值更改背景颜色
- php - Laravel 设置 Pdf 保护