私はランダムに数字を選択し、それを推測するようにユーザーに求め、ユーザーの選択に基づいて(大きい、小さい...)指示を与える小さなゲームに取り組んでいます。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);
}