即使在播种后,随机数发生器也会生成相同的数字

时间:2018-02-27 18:26:37

标签: c++

这是我的代码:

#include <iostream>
#include <string>
#include <random>
#include <ctime>

using namespace std;

int RandomIntGen(int lowerLimit, int upperLimit);

int main()
{
    for (int i = 0; i < 10; i++) {
        cout << "I am rolling a " << RandomIntGen(1, 6) << endl;
    }

    system("PAUSE");
}

// A random integer generator that takes in a upper and lower integer limit and returns a random integer
int RandomIntGen(int lowerLimit, int upperLimit) {
    default_random_engine randomGenerator(time(0)); //seeding with time
    uniform_int_distribution<int> randomInteger(lowerLimit, upperLimit);
    return randomInteger(randomGenerator);
}

不知道为什么即使播种也会产生相同的值。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

已移动“default_random_engine randomGenerator(time(0));”到全球空间,以确保它只播种一次。

#include <iostream>
#include <string>
#include <random>
#include <ctime>

using namespace std;

//Random Generator with Seed
default_random_engine randomGenerator(time(0));

// Function Declarations
int RandomIntGen(int lowerLimit, int upperLimit);

int main()
{

    for (int i = 0; i < 10; i++) {
        cout << "I am rolling a " << RandomIntGen(1, 6) << endl;
    }

    system("PAUSE");
}

// A random integer generator that takes in a upper and lower integer limit and returns a random integer
int RandomIntGen(int lowerLimit, int upperLimit) {
    uniform_int_distribution<int> randomInteger(lowerLimit, upperLimit);
    return randomInteger(randomGenerator);
}