我正在研究一个随机选择数字的小游戏,然后要求用户猜测它,根据用户的选择给出指示(更大,更小......)。要生成0到100之间的随机数,我使用以下代码:
int random = rand() % 101;
这很好用,但唯一的问题是这个变量经常被重新分配不同的值。我该如何防止这种情况?
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int tries;//number of tries allowed
bool win;//whether the user has won the game or not
int main(){
string gameType;
cout << "Please enter your game type; \"easy\", \"medium\", \"hard\", and \"expert\"." << endl;
cin >> gameType;
if(gameType == "easy"){
tries = 40;
cout << "You have 40 tries." << endl;
}else if (gameType == "medium"){
tries = 20;
cout << "You have 20 tries." << endl;
}else if (gameType == "hard"){
tries = 10;
cout << "You have 10 tries." << endl;
}else if (gameType == "expert"){
tries = 5;
cout << "You have 5 tries.";
}
cout << "Please enter a number between 0 and 100." << endl;
while (win == false){
int random = rand() % 101;//random number generation between 0 and 100
return(random);
bool valid = false;//if the user's number is valid (0 >= ; <= 100)
int usedTries = 0;//the tries that the user has used up
int selection;
cin >> selection;
if (selection > 100){
cout << "Your number cannot be above 100." << endl;
valid = false;
}else if (selection < 0){
cout << "Your number cannot be below 0";
valid = false;
}else{
valid = true;
}
if (valid == true){
if (selection > random){//bigger than target number
cout << "Smaller!" << endl;
usedTries = usedTries + 1;
}else if (selection < random){//smaller than target number
cout << "Bigger!" << endl;
usedTries = usedTries + 1;
}else if (selection == random){//the user has guessed the right answer
cout << "Yay! You win!" << endl;
win = true;
}
if (usedTries >= tries){//user has used up his number of tries
cout << "Sorry, you've lost the game. Try again later." << endl;
win = false;//to end the loop and terminate the game
}
}
}
return(0);
}
答案 0 :(得分:2)
执行作业时,只会为其分配一个新值。根据您的描述,它被分配在一个循环中。您可能希望将分配移出循环。
典型结构如下:
答案 1 :(得分:1)
正如其他人所指出的,你应该只分配一次。无论哪种方式,您都可以将其更改为:
static int random = rand() % 101;
那只会分配一次。
答案 2 :(得分:0)
如果你有相同的后续数字并想要真正的radom值,你应该在调用srand
之前使用rand
函数至少一次。传递给srand
一些随机值,简单的方式是以秒为单位传递当前时间等。