猜随机数游戏
Guess the random number game
我正在制作一个猜数字游戏,我不知道如何结合一定数量的猜测,用户必须得到正确的答案。我希望用户只有 3 次猜测来猜测数字,但在 3 次猜测之后,如果他们没有得到正确的,他们就会输。这是我下面的代码:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand ( time(NULL) );
cout << "Select a difficulty: 1) Easy, 2) Medium, 3) Hard " << endl;
int userlevel;
int userinput;
int randomNumber;
cin >> userlevel;
{
if (userlevel==1)
cout << "You chose Easy: 3 chances to guess correctly" << endl;
cout << "Pick a number between 1 and 10: " << endl;
cin >> userinput;
randomNumber = rand() % 10 + 1;
if (randomNumber==userinput)
cout << "You, guessed correctly! You win!" << endl;
else
cout << "I'm sorry, that is not correct. You lose." << endl;
}
{
if (userlevel==2)
cout << "You chose Medium: 4 chanaces to guess correctly" << endl;
cout << "Pick a number between 1 and 50: " << endl;
cin >> userinput;
randomNumber = rand() % 50 + 1;
if (randomNumber==userinput)
cout << "You, guessed correctly! You win!" << endl;
else
cout << "I'm sorry, that is not correct. You lose." << endl;
}
{
if (userlevel==3)
cout << "You chose Hard: 5 chances to guess correctly" << endl;
cout << "Pick a number between 1 and 100: " << endl;
cin >> userinput;
randomNumber = rand() % 100 + 1;
if (randomNumber==userinput)
cout << "You, guessed correctly! You win!" << endl;
else
cout << "I'm sorry, that is not correct. You lose." << endl;
}
return 0;
}
你应该研究一下while循环。它将像这样使用:
int main() {
//...everything above this in yours is good
int Number_to_guess = (rand() % 10 + 1);
int NChances = userlevel + 2;
cout << "You have " << NChances << " chances to guess right.n";
while (NChances != 0)
{
cout << "Guess: ";
cin >> userinput;
if (userinput == Number_to_Guess) {
cout << "You win! Congrats!n";
break; // this will break out of the while-loop
}
NChances--; // this will count down the chances left
}
if (NChances == 0) {
cout << "Sorry, you lose. Try again next time!n";
}
return 0;
}
你在这里缺少的主要想法是围绕猜测限制的循环。因此,在弄清楚它们是什么级别之后,您可以说出类似于以下伪代码的内容:
While (counter <= 3)
*Your If Statements*
counter = counter +1
确保在他们猜对数字的 if 语句中,尽早将它们从循环中解脱出来。
最后,在进入循环之前猜测一个数字可能更有意义。所以,就像他们选择难度一样,根据他们说的话选择随机数,然后循环开始。现在的方式是,每次通过循环都会创建一个新的随机数。我不确定这是否是有意的。
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 整数不会重复超过随机数
- 在C++游戏中与库存系统作斗争
- if数组上的随机数
- 换位表导致测试失败(但在游戏中运行良好)
- 在将数字随机生成为数组期间从内存输出随机数的数组
- Craps游戏问题,忽略if语句
- 半随机数生成C++
- 矢量下标超出SFML游戏中的范围
- 我是 c++ 的新手.学习基本知识后,我想做井字游戏.对于印刷板,我在下面写代码,但它显示错误
- 贪吃蛇游戏 - 食物瓷砖的随机数生成器
- 随机数生成器游戏
- 在此过程中的纸牌游戏程序.不知道为什么我会得到一个随机数-858993460
- 猜随机数游戏
- 我简单的 c++ 文本游戏不起作用。我正在使用随机数生成,我很困惑
- C++随机数猜谜游戏
- C++随机数猜测游戏-变量未声明错误
- 猜谜游戏,电脑产生随机数
- 随机数游戏
- 为猜谜游戏生成一个随机数生成器