我的RNG值确定了意外值

时间:2019-07-05 09:38:32

标签: 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.

2 个答案:

答案 0 :(得分:1)

您忘记考虑时间-在使用生成器之前,您需要给生成器添加种子,但是您将它作为程序中的最后一件事来做。

即使您首先在srand中移动main,该程序也将无法运行,因为您的全局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;
} 

答案 1 :(得分:1)

这里有很多错误:

1)您必须在调用srand()之前调用rand() 来植入随机生成器。目前,您在{em>之后呼叫srand()。因此,您将始终从rand()获得相同的数字序列。

2)time(0)是相当糟糕的种子。它的分辨率只有1秒,因此两个人都在同一秒内启动程序,将获得相同的伪随机数。这也是一个非常容易猜测的种子。

3)如果int randValPlayer = rand() % 20 + 1;的输出范围不能被20整除,则在rand()之类的语句中使用模数会产生偏差。

4)rand()(通常)周期较短且输出范围有限。结合使用std::mt19937std::uniform_int_distribution可能会更好。请参见链接页面上的示例。