0

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

3 回答 3

2

只有在您执行分配时,它才会被分配一个新值。根据您的描述,它是在循环内分配的。您可能希望将分配移出循环。

典型的结构类似于:

  1. 调用 srand
  2. 生成随机数
  3. 从用户那里得到猜测
  4. 如果猜错了,转到3
  5. 如果用户想再去,转到2
于 2012-12-17T20:26:29.933 回答
1

正如其他人指出的那样,您应该只分配一次。无论哪种方式,您都可以将其更改为:

static int random = rand() % 101;

那只会分配一次。

于 2012-12-17T20:33:14.270 回答
0

如果您有相同的结果数并且想要真正的随机值,您应该srand在调用之前使用函数rand至少一次。传递给srand一些随机值,简单的方法是以秒为单位传递当前时间等。

于 2012-12-17T20:26:47.107 回答