简单的数字猜游戏.c++
Simple Number Guessing Game. C++
我一直在尝试制作一个简单的游戏,其中计算机生成一个随机数,您尝试猜测它。它还会存储你"尝试"猜测的次数。
然而,当我运行程序时,它只是打印:"让我们玩一个游戏。我想一个数字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;
}
}
我不明白为什么这不起作用,有人能解释一下吗?
程序在"Let's play a game "之后不打印任何内容的原因。我想一个数字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;这将只生成正整数。
这里应该使用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);
你的for循环是错误的(它需要3件事:初始化,检查条件和每个循环后的todo步骤。例如:
for (tries = 0; tries < 5; tries++)
你也循环猜测部分,但你忘了问用户一个新的数字。我建议将cin << guess
移到for循环中。
相关文章:
- 在C++游戏中与库存系统作斗争
- 换位表导致测试失败(但在游戏中运行良好)
- Craps游戏问题,忽略if语句
- 矢量下标超出SFML游戏中的范围
- 我是 c++ 的新手.学习基本知识后,我想做井字游戏.对于印刷板,我在下面写代码,但它显示错误
- 我在贪吃蛇游戏中收到了错误代码 -1073741571
- 我应该在简单的策略游戏中为各个派系使用类吗 - C++
- 游戏体验和升级
- 我的代码运行良好,但在游戏循环中中断
- 如何使用 SFML 在贪吃蛇游戏中定义游戏结束?
- 在C++不适用于猜数字游戏的情况下再次播放选项
- 试图创建一个体面的基本刽子手游戏。猜出的字母不会取代短语中的字母
- C++随机猜数游戏错误
- 猜随机数游戏
- 猜数字游戏
- 如何保持跟踪字母已经猜到了在猜字游戏为c++
- 简单的数字猜游戏.c++
- 随机生成器猜游戏
- C++猜数字游戏在其他计算机上崩溃并无限循环修复
- C++猜游戏错误