At the following: http://www.fredosaurus.com/notes-cpp/misc/random.html
It mentions that if we want to generate a random number in the range 1-10
, we ca
You add 1, because you want random number 1-10, not 0-9, what will %
do without the +1
.
For example, 10 % 10 == 0
and 9 % 10 == 9
, so this gives you 0-9.
Adding +1
will "move" this interval to 1-10-> 10 % 10 + 1 == 1
and 9 % 10 + 1 == 10
EDIT: Sorry, forgot about you srand
question.
rand()
generates the same sequence of numbers, unless you call srand
and "seed" the random number generator with different value, before calling rand()
. So, here time(0)
seeds the random number generator with the current time, that gives you different value for all the times, you call rand()