Hello! I have one problem that I don't understand:
I need to generate some random numbers so I use:
1 2 3
#include <ctime>
srand(time(0));
int r = (rand() % n);
The problem is that I need it in the class. So I just use srand(time(0)) in class constructor and (rand() % n) in other class member void function. It generates random number, but every time same random numbers. For example if one object generate 9, 4, 0, 8 and other object generate same numbers 9, 4, 0, 8...
Maybe someone can help me?
Thanks in advance!
rand() implements a linear congruential random number generator (LCRNG). An LCRNG uses the generator function
R(n) = ( c * R(n-1) + k ) mod p
where
c and k are carefully chosen constants.
p is 2^32 for 32-bit machines.
R(n) is the nth random number and R(n-1) is the previous random number.
R(0) is hardcoded in the C library. srand() changes the value of R(0) to the value passed in.
An LCRNG, as do all PRNGs (Pseudo-RNGs), generates the same series of random numbers each time R(0) is set to a given value V.
time() returns the number of seconds elapsed since Jan 1, 1970. Obviously this value changes only once a second. Your code is probably fast enough that it reseeds R(0) with the same second value several times.
You should call srand() exactly once in your program.