C++ 的新手,这是学校的作业。我应该做一个猜谜游戏,显示以下消息:
You are too cold on lower side (display -----)
You are hot on lower side (display ---)
You are hot on the upper side (display +++)
You are too cold on the upper sire (display +++++)
YOU ARE THERE (######YOU WON ####)
在我输入我的猜测后,我不断收到“+++++++++...”或“-----...”的墙,我不明白为什么。这是我到目前为止的代码:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int num, guess;
bool correct = false;
srand((int)time(0));
//generating random number 1-100
num = rand()%100+1;
cout<<num;
cout<<"Let's play a game! I'll think of a number and you can try to guess it."<<endl;
cout<<"Let's begin! I'm thinking of a number 1-100. What's my number?"<<endl;
cin>>guess;
while(correct==false)
{
if(guess<num)
{
cout<<"---";
}
if (guess<(num/2))
{
cout<<"-----";
}
if(guess>num)
{
cout<<"+++";
}
if (guess>(num+num/2))
{
cout<<"+++++";
}
if(guess==num)
{
cout<<"########YOU WON!########";
correct=true;
}
}
}
任何帮助将不胜感激。谢谢!
最佳答案
我不确定实现此猜谜游戏所需的所有详细信息,但我可以说的是。如果您在第一次尝试时没有猜出正确答案,就会陷入无限循环。这是因为你的 while
循环条件基于一个 bool 值,该 bool 值仅分配给用于猜测正确答案的条件(您在 if
循环中的最终 while
语句)。
其次,您的 if 语句每次迭代可以打印多个字符串。例如,如果用户猜测 10
随机数是80
, 前两个 if 语句将为真,并且自 10 < 80
起将打印它们是真的 10 < 80/2 //ie 40
也是如此。考虑按条件嵌套您的 if 语句。
话虽如此,这是我运行的一个实现。通读这段代码并理解它。我在 while 循环中为用户添加了一个提示,以便用户可以一直猜测数字直到正确为止。希望这可以帮助。
注意:我没有对此代码进行深入测试,因为这是一项任务,您有责任根据需要理解和调试代码。
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int num, guess;
srand((int)time(0));
//generating random number 1-100
num = rand()%100+1;
cout<<num<<endl;
cout<<"Let's play a game! I'll think of a number and you can try to guess it."<<endl;
cout<<"Let's begin! I'm thinking of a number 1-100. What's my number?"<<endl;
cin>>guess;
while(guess != num)
{
if(guess<num)
{
if (guess <(num/2))
{
cout<<"-----"<< endl;
}
else{
cout<<"---"<< endl;
}
}
if(guess>num)
{
if (guess>(num+num/2))
{
cout<<"+++++"<< endl;
}
else{
cout<<"+++"<< endl;
}
}
cout<<"Guess again" << endl;
cin >> guess;
}
cout<<"########YOU WON!########";
}
关于C++数字猜谜游戏 - 来自if语句的循环文本墙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51054187/