猜谜游戏,电脑产生随机数
Guessing game where computer generates random number
我正在实现一个猜谜游戏,其中计算机生成随机数与以下代码:
int main()
{
srand(time(NULL));
while (true){
int num = rand() % 10, guess, tries = 0;
while (true){
cout << "Enter number 1 to 10:";
cin >> guess;
if (tries > 2)
{
break;
}
if (guess > num)
{
cout << "Too High ! Try again"<<endl;
}
if (guess > 10)
{
cout << "Error ReEnter 1 to 10n";
}
else if (guess < num)
{
cout << "Too Low! Try again"<<endl;
}
else
{
break;
}
tries++;
}
if (tries > 2)
{
cout <<"nYou ran out of tries!n";
cout << "nThe answer is:" << num << endl;
}
else
{
cout << "nCONGRATZ!! You guess correctly!n";
}
return 0;
}
}
其中一个问题是:当用户尝试3次时,即使用户在第三次尝试时输入正确,程序仍显示"run out of tries"。
问题:
1。我如何通知用户他们的输入超过了10,并显示一条错误消息,让用户输入从1到10的值?
2。如何纠正上述问题?
这里是一些伪代码,而不是为您编写程序。
get a random number rand()%10+1 1..10 call it R
loop
get user input N
if N == R then show OK and break loop
if N < R show too low
else show too high
increment tries
if tries == 3 then break loop
end loop
你有太多的if else
条件,使你的代码不必要地复杂,回答你的第二个问题,特别是不需要的行为是由:
if (tries > 2)
{
break;
}
退出循环,而不考虑猜测,因为它只依赖于尝试的次数。关于你的第一个问题,我决定为你提供一个更简单的实现,包括它的答案。
您可以将while
循环替换为do-while
循环,当猜出随机数时终止,即:
int main(){
// initialize random seed
srand (time(NULL));
// generate a random number within [1,10]
int secretRandom = rand() % 10 + 1;
// initialize
int yourGuess = 11;
// input loop
string promptMessage = "Type a a number from 1 to 10."
do{
cout << promptMessage << 'n';
// read input
cin >> yourGuess >> endl;
// guessed number relatively to the randomly generated
if (secretRandom < yourGuess) cout << "The secret number is lowern";
else if (secretRandom > yourGuess) cout << "The secret number is highern";
}while(yourGuess != secretRandom)
// if you guess the random number exit the loop and display success message
cout << "You guessed right!n";
return 0;
}
为了减少对特定数字的猜测量,您可以将do-while
循环和成功消息包含在for
循环中,例如:
int numberOfGuesses = 3;
for (int i = 0; i <= numberOfGuesses; ++i){
//...
}
如果你想强制用户输入1到10之间的数字,你可以这样做:
int yourGuess = 11;
int lowerBound = 0;
int upperBound = 10;
do{
cin >> yourGuess;
// not type safe
}while(yourGuess < lowerBound || yourGuess > upperBound);
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 整数不会重复超过随机数
- C++在变量给定的指定时间内关闭电脑
- if数组上的随机数
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 半随机数生成C++
- 程序在尝试猜测它选择的随机数时进入无限循环?
- 有没有办法在 c++ 中同时生成随机数?如果没有,是否有解决方法?
- 具有随机数的二维数组不会更改
- 随机数未达到限制
- 我想生成许多矩阵并用随机数填充它
- <random>在实践中应该实际使用哪个随机数引擎? std::mt19937?
- 制作具有平均值的随机数生成器
- C++代码在台式机上工作正常,但在笔记本电脑上则不行
- 为什么 rand 不在我的代码中生成随机数?
- C++ 随机数生成器:尝试将结果作为向量获取,但通过制作 void 函数来执行此操作而出现错误
- 从给定种子生成相同的随机数序列C++
- 随机数生成函数说明
- C++ 尝试生成随机数时弹出警告帮助?
- 猜谜游戏,电脑产生随机数