我一直试图制作一个简单的游戏,计算机生成一个随机数,你试着猜它。它还存储您“尝试”的猜测量。
然而,当我运行该程序时,它只是打印:“让我们玩游戏。我会想到一个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;
}
}
我不明白为什么这不起作用,有人可以解释为什么不呢?
你应该在这里使用while
循环,而不是for
:
while (the_number != guess)
{
//
//
}
并尝试使用新的<random>
头而不是rand()
函数:
#include <random>
std::random_device rd;
std::default_random_engine engine(rd());
std::uniform_int_distribution<int> uniform_dist(1, 100);
the_number = uniform_dist(engine);
在“让我们玩游戏之后你的程序没有打印任何东西的原因。我会想到一个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;
}
}
您可以定义一些变量,使您的代码更容易理解,如下所示:
#include <iostream>
using namespace std;
int main()
{char EndGame = 'N';
int MyNumber = 150 , playerguess;
cout << "I have a number between 1 and 100.\nCan you guess my number ??\nPlease type your first guess.\n?" << endl;
do{
cin >> playerguess;
if (playerguess > MyNumber) {
cout << " Too High. Try again." << endl;
}
else if (playerguess == MyNumber) {
cout << "Excellent ! You Got It ! \n If you want to exit press Y" << endl;
cin >> EndGame;
break;
}
else {
cout << " Too Low. Try again." << endl;
}
} while (1);
return 0;
}
这将使数字等于150.每次用户输入一个值时,控制台将确定它是否高于,低于或等于该数字。
如果你想改为每次都是一个随机数,你可以简单地使用<random>
库并使用模块运算符和100或101之类的数字。然后,你可以添加1;这将只生成正整数。
你的for循环是错误的(它需要3件事:初始化,检查条件和每个循环后的todo步骤。例如:
for (tries = 0; tries < 5; tries++)
您也可以循环猜测部分,但是忘记向用户询问新号码。我建议将cin << guess
移动到for循环中。