我正在开发一个随机选择一个数字的小游戏,然后要求用户猜测它,并根据用户的选择(更大,更小......)给出指示。要生成 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);
}