我一直在尝试制作一个简单的游戏,让计算机生成一个随机数,然后您尝试猜测它。它还存储您进行“尝试”的猜测数量。
但是,当我运行该程序时,它只是打印:“让我们玩一个游戏吧。我会想一个数字 1-100。试着猜一猜。”
这是我的代码:
#include <iostream>
int main()
{
using namespace std;
int the_number;
int guess;
int tries;
the_number = rand() % 101 + 1;
cout << "Let's play a game!";
cout << "I will think of a number 1-100. Try to guess it.";
cout << endl;
cin >> guess;
for (tries = 0; tries++;)
{
if (guess == the_number)
{
cout << "You guessed it!";
cout << "And it only took you: " << tries;
}
else if (guess < the_number)
{
cout << "Higher";
tries++;
}
else if (guess > the_number)
{
cout << "Lower";
tries++;
}
else
cout << "That's not even in range!";
return 0;
}
}
我不明白为什么这行不通,有人可以解释为什么不行吗?
最佳答案
您的程序在“让我们玩一个游戏吧。我会想出一个数字 1-100。试着猜猜”之后没有打印任何内容的原因。是您编写 for
循环的方式。
for ( tries = 0; tries++; )
因为 tries++
的计算结果为 0
,所以不做任何事情就跳出了循环。
此外,为了让您的程序正常运行,您需要添加更多代码来读取猜测。类似于下面的代码,应该可以工作。
for (tries = 0; ; tries++)
{
if (guess == the_number)
{
cout << "You guessed it!";
cout << "And it only took you " << tries << " tries.\n";
break;
}
else if (guess < the_number)
{
cout << "Higher";
cin >> guess;
}
else if (guess > the_number)
{
cout << "Lower";
cin >> guess;
}
}
关于c++ - 简单的数字猜谜游戏。 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24837559/