Pergunta

#include <time.h>
((unsigned)time(NULL));

I don't understand why you have to include the time header file and use the time function in your program when creating a pseudo-random number generator using the function srand(). Can somebody please explain what the significance of time is in this case?

* Please note that the code shown is only part of the program. Thank you.

Foi útil?

Solução 2

It makes the code non-repeatable when it is called for a second time. If you include no seed or a fixed number for a seed, the program will act exactly the same, because the random number will be the same.

Outras dicas

It's because of the Pseudo- part of Pseudorandom. The PRNG performs a mathematical operation upon an internally-stored seed value to yield the next output number and transform the seed.

If you don't call time(NULL) or some other source of entropy (eg. /dev/rand), then the sequence will still be pseudo-random (not easily predictable by examining the values), but it will be exactly the same for every run of the program. Because, even though it may be very difficult to accurately predict the next number, it is possible because the PRNG is deterministic.

If you don't provide your own seed with srand(), the default initial seed is usually 1.

The time() call provides the initial source of entropy that makes the starting seed unpredictable.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top