The C++
rand()
function uses a reasonably simple algorithm to return a random number between 0 and
RAND_MAX
, which differs between platforms.
For the algorithm to work, you need to seed it with a number. Call it a basis from which the algorithm can do its work.
If you seed it with a fixed number, you'll get the same results each time the program runs. The math behind the algorithm is fixed, so if your program gives it the same seed every time, you're going to get the same results every time, which is what is currently happening in your code.
A common way to get a pseudo-random value is to seed the generator using the system clock, as
Zhuge pointed out.
The value will be differ between runs of the program as the system time will be different.
You then call the
rand()
function to get your random number and limit the range using the modulus operator. The maths to this is quite obvious, but give me a shout if you need me to explain further.