Call srand () twice in one program

why does this happen when i call srand () at 2 very different points, this leads to the fact that the numbers are not random? As soon as I delete one of them, it will return to its normal state.

+3
source share
4 answers

It depends on how you call it. The goal srand()is to populate the pseudo random number generator used rand(). Therefore, when you call srand(i), it initializes a rand()fixed sequence, which depends on i. Therefore, when you re-sow with the same seed, you start to get the same sequence.

The most common case is generator seeds only once and with a suitable "random" value (for example, idiomatic time(NULL)). This guarantee makes it likely that you will receive different sequences of pseudorandom numbers in different program executions.

However, sometimes you may need to make the pseudo-random sequence β€œplayable”. Imagine you are testing several random data sorting algorithms. To get fair comparisons, you must test each algorithm on the same data, so you must reseed the generator with the same seed before each run.

: , , . - , .

+7

srand? / :

srand(time(NULL));

:)

0

, srand-rand - . , - . srand() . . , . , , , . - .

#include <time.h>

srand((unsigned int)time(0));
0

All Articles