for循环中的随机数生成器每次都给出相同的数字

Random number generator in a for loop gives same numbers each time

本文关键字:数字 循环 随机数生成器 for      更新时间:2023-10-16

这个程序应该是一个非常原始的老虎机,有三个不同的"轮子"可以旋转。每个轮子都包含一定数量的字符。函数生成一个随机数,将其指定为每个车轮中的阵列位置,然后生成与该位置对应的符号。

我遇到的问题是,随机生成的数字在for循环的每次迭代中都不会改变。所以我基本上每次循环都会得到"X-X"或"X@-"。我搜索了以前提出的问题,找到了几个相关的问题,但似乎没有一个能解决我的特定问题。

为长代码道歉:

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
const int WHEEL_POSITIONS = 30;
const char wheelSymbols[WHEEL_POSITIONS + 1] = "-X-X-X-X-X=X=X=X*X*X*X*X@X@X7X";
struct slotMachine
{
    char symbols[WHEEL_POSITIONS + 1];
    int spinPos;
    char spinSymbol;
} wheels[3];
void startWheels(slotMachine []);
void spinWheels(slotMachine []);
void displayResults(slotMachine []);
bool getWinner(slotMachine []);
int main(void)
{
    int spinNum;
    cout << "How many times do you want to spin the wheel? ";
    cin >> spinNum;
    // Calls startWheels function
    startWheels(wheels);
    for (int i = 0; i < spinNum; i++)
    {
        // Calls spinWheels function
        spinWheels(wheels);
        // Calls displayResults function
        displayResults(wheels);
        // Calls function getWinner; if getWinner is true, outputs winning message
        if (getWinner(wheels) == true)
        {
            cout << "Winner! Matched 3 of " << wheels[0].spinSymbol << "." << endl;
        }
    }
    return 0;
}
// Function to initialize each wheel to the characters stored in wheelSymbols[]
void startWheels(slotMachine fwheels[3])
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < (WHEEL_POSITIONS + 1); j++)
        {
            fwheels[i].symbols[j] = wheelSymbols[j];
        }
    }
}
// Function to generate a random position in each wheel
void spinWheels(slotMachine fwheels[3])
{
    time_t seed;
    time(&seed);
    srand(seed);
    for (int i = 0; i < 3; i++)
    {
        fwheels[i].spinPos = (rand() % WHEEL_POSITIONS);
    }
}
void displayResults(slotMachine fwheels[3])
{
    for (int i = 0; i < 3; i++)
    {
        fwheels[i].spinSymbol = fwheels[i].symbols[(fwheels[i].spinPos)];
        cout << fwheels[i].spinSymbol;
    }
    cout << endl;
}
bool getWinner(slotMachine fwheels[3])
{
    if ((fwheels[0].spinSymbol == fwheels[1].spinSymbol) && (fwheels[0].spinSymbol == fwheels[2].spinSymbol) && (fwheels[1].spinSymbol == fwheels[2].spinSymbol))
    {
        return true;
    }
    else
    {
        return false;
    }
}

我确信我错过了一些简单的东西,但我找不到!

每次调用函数spinwheels时,都会重新设定随机数生成器的种子。

将这三行移动到main函数的顶部。

   time_t seed;
   time(&seed);
   srand(seed);

当我们使用rand()生成随机数时,我们实际上使用的是伪随机数生成器(PRNG),它基于称为seed的特定输入生成一个固定的随机值序列。当我们设置种子时,我们有效地重置了序列,使其再次从同一种子开始。

您可能会认为,使用time每次都会产生不同的种子,这仍然会每次都给您带来不同的结果,但在快速计算机程序中,时间过得太少,以至于每次调用时种子实际上都没有变化。

这就是为什么,正如另一个答案所提到的,您应该在程序中只调用srand()一次。

您应该在程序中只调用srand()一次,而不是每次都要生成随机数。

如果你在短时间内通过time()重新设定rand()的种子,你最终只会重新启动序列,并重复获得第一个值。