c++ - 我的 RNG 值确定意外值

标签 c++

我知道随机并不是真正随机的,因此实现了随时间变化的 srand,但是它并不是在我每次运行程序时都给出随机值,而是完全相同的值 92 和 98,或者更确切地说是 2 和 8。我想要我的变量 int randValPlayer = rand() % 20 + 1;int randValCPU = rand() % 20 + 1; 给随机值。

我将 srand(time(0)); 放在我的主要函数中。我尝试更改预期值的随机算法。

class Game 
{
private:
    int playerHealth = 100;
    int cpuHealth = 100;
    int userChoice;
    int randValPlayer = rand() % 20 + 1;
    int randValCPU = rand() % 20 + 1;
public:
    int attackPlayer()
    {

        playerHealth = playerHealth - randValPlayer;
        return playerHealth;
    }
    int attackCPU()
    {

        cpuHealth = cpuHealth - randValCPU;
        return cpuHealth;
    }
    void choice() 
    {
        cout << "Input '1' to attack CPU" << endl;
        cin >> userChoice;
        if (userChoice == 1)
        {
            attackCPU();
            cout << "CPU's health reduced to " << cpuHealth << endl;
            attackPlayer();
            cout << "Player health reduced to " << playerHealth << endl;
            system("pause");
        }
    }
}gameobj;

class Foundation 
{
private:
    int userChoice;

public:
    void startProgram() 
    {
        cout << "Please input desired number: " << endl;
        cout << "1. Calculator" << endl;
        cout << "2. Equation calculator" << endl;
        cout << "3. Game" << endl;
        cin >> userChoice;
        system("cls");
        if (userChoice == 1) {
            calcobj.calcOperation();
        }
        if (userChoice == 2) {
            equationobj.equationChoice();
        }
        if (userChoice == 3) {
            gameobj.choice();
        }
    }
}foundobj;

int main()
{
    foundobj.startProgram();
    srand(time(0));
    return 0;
} ```

I expected the output to be random but the integer values are just the exact same, via 8 and 2.

最佳答案

您忘了考虑时间 - 您需要在使用生成器之前为生成器播种,但您将其作为程序中的最后一件事来执行。

即使您先在 main 中移动 srand,此程序也不会运行,因为您的全局 Game 实例是在此之前创建的。

由于(可变的)全局变量通常不是一个好主意,所以这是重写的好机会。

我建议这样:

class Game
{
   // ...
};

class Foundation 
{
private:
    Game gameobj;
    // The other objects here...
public:
    void startProgram() 
    {
        int userChoice = 0;
        cin >> userChoice;
        // ...
        if (userChoice == 3) {
            gameobj.choice();
        }
    }
};

int main()
{
    srand(time(0));
    Foundation foundobj;
    foundobj.startProgram();
    return 0;
} 

关于c++ - 我的 RNG 值确定意外值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56900451/

相关文章:

C++ 从另一个模板函数调用模板函数

C++ 常量引用语义?

C++ 在主函数中初始化静态变量

c++ - Boost Property Tree 是否有为要解析的数据定义规则的方法?

c++ - UML 图上数组的表示数组

c++ - std::array<T> 初始化

c++ - SIGTSTP 信号不阻止 child ?

c++ - 段错误 : stack overflow

c++ - 解释此 C++ 函数中的程序流程

c++ - 移除 std::future 和 std::promise 的无效特化