나는 임의로 숫자를 선택하는 작은 게임을 작업하고 있으며 사용자가 그것을 선택하여 사용자의 선택에 따라 표시합니다 (더 크고 작음 ...) .랜덤 화 된 정수가 지속적으로 재 할당되는 것을 방지합니다.
int random = rand() % 101;
이 잘 작동하지만 유일한 문제는이 변수가 지속적으로 다른 값을 재 할당되고 있다는 점이다 : 0에서 100 사이의 임의의 숫자를 생성하려면 다음 코드를 사용하고 있습니다. 이 문제를 어떻게 방지 할 수 있습니까?
#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);
}
"지속적으로 다른 값을 다시 할당 하시겠습니까?"라는 의미에 대해 자세히 설명 할 수 있습니까? 지금 당장은 네가 무엇을 요구하는지 모르겠다. – templatetypedef
메인 플레이 루프에서 과제를 가져 오겠습니까? –
... 두 번 이상 할당하지 않습니까? 질문이 의미가 없기 때문에 아마 더 많은 코드를 보여 주어야합니다. – Bwmat