20个问题游戏
20 Questions Game
我被指派用C++编写一段代码,用户必须猜测1-100之间的数字,然后计算机有20个问题来尝试猜测这个数字。这是我写的代码:
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int imax;
char ans;
int imin;
int i;
const char y = 'y';
const char n = 'n';
imax = 100;
imin = 0;
i = 0;
int e = (imax - imin) / 2;
cout << "Think of a number between 1-100." << endl;
do
{
cout << "Is the number equal or greater too " << e << endl;
cin >> ans;
if (ans == y)
{
cout << "Is the number " << e << endl;
cin >> ans;
if (ans == y)
{
i = e;
return i;
}
else
{
imin = e;
}
}
else
{
imax = e;
}
} while (i == 0);
cout << "Your number is "<< i << endl;
system("PAUSE");
return 0;
}
代码一直工作到到达第二个if语句。它会接受一个"y"并询问数字是否为e,但如果回答了"n",它也不会改变亚胺e。此外,如果第一个if语句回答了"n",它不会将imax也设置为相等。我已经为此挣扎了很长一段时间,非常感谢您的帮助。
您没有在循环中更改e
的值,这就是为什么它在else
条件下什么都不做的原因。你的逻辑也有点错误。试试这个,希望这会有所帮助:
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int imax;
char ans;
int imin;
int i;
const char y = 'y';
const char n = 'n';
imax = 100;
imin = 0;
i = 0;
cout << "Think of a number between 1-100." << endl;
do
{
int e = imin + ((imax - imin) / 2);
cout << "Is the number equal or greater too " << e << endl;
cin >> ans;
if (ans == y)
{
cout << "Is the number " << e << endl;
cin >> ans;
if (ans == y)
{
i = e;
break;
}
else
{
imin = e;
}
}
else
{
imax = e;
}
} while (i == 0);
cout << "Your number is "<< i << endl;
system("PAUSE");
return 0;
}
EE 273是一场噩梦。我在其他地方找到了这个代码:
#include<iostream>
using namespace std;
const int MAX_VALUE = 100;
const int MIN_VALUE = 1;
int guess;
int high = MAX_VALUE;
int low = MIN_VALUE;
char choice;
int main(){
cout<<"Think about a number between "<<MIN_VALUE<<" and "<<MAX_VALUE<<". nn";
guess = ( high-low ) / 2;
while((high-low)!=1){
cout<<"Is your number less than or equal to "<<guess<<"? nEnter y or n. nn";
cin>>choice;
if(choice=='y' || choice=='Y') {
high = guess;
guess -= ( high - low ) / 2;
}
else if(choice=='n' || choice=='N') {
low = guess;
guess += (high - low ) /2;
}
else cout<<"Incorrect choice."<<endl;
}
cout<<"Your number is: "<<high<<".n";
system("pause");
return 0;
}
相关文章:
- Craps游戏问题,忽略if语句
- Frank Luna 在他的书"使用 DirectX12 进行 3D 游戏编程"的介绍中盒子示例的问题
- 我正在尝试创建一个 C++ 贪吃蛇游戏,但我似乎无法绘制第二个高度边框,我该如何解决这个问题?
- C++游戏中的 UDP 通信问题
- 将四元数旋转的游戏对象旋转另一个四元数时出现问题
- 创建堆栈时出现问题!(街机游戏)
- 游戏引擎设计问题
- C++ do/while 循环和 if/else: 骰子游戏 -- 第 75 行错误:"Cout"之前的预期"While" -- 如何解决这个问题?
- 使用虚幻引擎4编程的平台游戏中的偏转问题
- 简单的游戏数据库问题
- TCS 模拟生活 2019 第 2 轮问题:跳跃游戏
- 井字游戏的这个最小最大值实现有什么问题?
- 使用碰撞检测来增加SFML 2.4中的游戏分数的问题
- 跳跃游戏中嵌套的循环问题
- 地牢爬网游戏,运动机械问题
- 策划者游戏打印问题#
- 刽子手游戏的验证问题
- 隐藏游戏板报告描述符问题
- 生活中的游戏问题,C++
- 井字游戏-问题检测领带