c++ - 防止随机整数不断被重新分配

标签 c++

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

最佳答案

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

典型的结构是这样的:

  1. 调用srand
  2. 生成随机数
  3. 从用户那里得到猜测
  4. 如果猜错了,转到3
  5. 如果用户想再去一次,转到2

关于c++ - 防止随机整数不断被重新分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13921584/

相关文章:

c++ - 当brew安装opencv3时,我得到警告,该公式没有--with-contrib选项

c# - Visual Studio 2012 调试多个项目

c++ - Switch 语句 C++ 的问题

c++ - 我可以从initializer_list实例化一个数组吗?

c++ - 捕捉按键 C++

C++ Circular #include 前向声明未修复

C++ stringstream >> int 返回零

c++ - std::map 分配错误

c++ - 制作不同子类实例的 vector

c++ - 迭代计算集合或 vector 的幂集