0

The code is giving me the same number every time I run the program. I can't figure out why.

I looked up a tutorial on how to use the seed the generator properly, and for some reason my example won't work.

#include <iostream>
#include <random>

int returnRandomNumber(int to) {
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_int_distribution<> dist(0, to);

    return dist(mt);
}

int main() {

    int testNum;

    for (int i = 0; i < 10; i++) {

        testNum = returnRandomNumber(100);
        std::cout << testNum << "\n";

    }

}
John K
  • 21
  • 2
  • `std::random_device` used to be broken in MinGW GCC (gave the same numbers every time). It was fixed in GCC 9.2. Update your compiler. – HolyBlackCat Aug 05 '20 at 19:41
  • 4
    The random device, generator, and distribution must be re-used between iterations. Declare them at global scope or at least `static`. – rustyx Aug 05 '20 at 19:46
  • Since the range of the distribution can change, it likely can't be static. – sweenish Aug 05 '20 at 19:53
  • @sweenish You can change the range of an existing distribution. – HolyBlackCat Aug 05 '20 at 19:56
  • @HolyBlackCat How? – François Andrieux Aug 05 '20 at 19:59
  • @FrançoisAndrieux `foo.param(std::uniform_int_distribution<>::param_type(x,y));` I think. – HolyBlackCat Aug 05 '20 at 20:04
  • 1
    @HolyBlackCat I'm curious if this [resets](https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution/reset) the distribution. If `param_type` stores the full state of the distribution, then it would, and constructing a new instance would be equivalent. Otherwise, then that is an interesting approach. – François Andrieux Aug 05 '20 at 20:41

0 Answers0