rand() returns same values when called within a single function

You shouldn't call srand() before each call to rand(). Call it once – somewhere at the start of your program.

The problem is you restart the random generator so it starts to produce the very same pseudorandom sequence from the very same point.


The random number generator is reset to an initial state, which is dictated by the seed value, every time you call srand. Time value may be the same between successive calls to time, hence the same seed and the same number generated.

Call seeding function (srand) only once in your main function before generating random samples.


Why do you keep calling std::srand(time(0));? That re-seeds the PRNG.... and because this all happens within the same second, you're always re-seeding it with the same sequence.

Call srand once in your program, and once only.

Also, I would recommend, at least on POSIX-compliant systems, something like std::srand(time(0) ^ getpid()), so that you can run your program twice within the same "second" and still get a new PRNG sequence.

Tags:

C++

Random