Let's say you have millions of books with rows upon rows of random numbers.
Before you get a random number you need to select a book.
After you have a book, to get random numbers, read numbers sequentially from the book.
Changing the book gets another sequence of random numbers.
Changing to the same book restarts the sequence form the first number in the book.
srand()
chooses a book and starts random numbers from the beginning
rand()
reads the next number from the selected book
If you put srand()
inside the loop, you are effectively restarting the random number sequence from the beginning of the same book.
Solution: select 1 book once, and keep reading numbers from it for ever and ever.
In a C program, if you don't "select a book", the random numbers come from book #1 or, in other words, in the absence of a srand()
call, the function rand()
behaves as if srand(1)
has been called.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…