我的RNG值确定了意外值

My RNG value ascertains unexpected values

本文关键字:意外 RNG 我的      更新时间:2023-10-16

我知道随机并不是随机的,因此可以实现随时间的srand,但是每次运行程序时,它并不是随机值,而是完全相同的值92和98,或2和2。我希望我的变量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;
} 

这里有很多错误:

1(您必须通过调用srand() 的任何调用rand()来播种。当前,您在之后致电srand() 。因此,您将始终从rand()获得相同的数字顺序。

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

3(您在诸如int randValPlayer = rand() % 20 + 1;之类的语句中使用Modulo会引入偏差,如果rand()的输出范围不能均匀地除以20。

4(rand()(通常(的时间很短,输出范围有限。STD :: MT19937与std :: unibribil_int_distribution相结合,您可能会更好地为您服务。请参阅链接页面的示例。