Look at the source of srand()
from this question: Rand Implementation
Also, example implementation from this thread:
static unsigned long int next = 1;
int rand(void) // RAND_MAX assumed to be 32767
{
next = next * 1103515245 + 12345;
return (unsigned int)(next/65536) % 32768;
}
void srand(unsigned int seed)
{
next = seed;
}
As you can see, when you calling srand(time(0))
you will got new numbers on rand()
depends on seed. Numbers will repeat after some milions, but calling srand
again will make it other. Anyway, it must repeat after some cycles - but order depends on argument for srand
. This is why C rand isn't good for cryptography - you can predict next number when you know seed.
If you have fast loop, calling srand
every iteration is without sense - you can got same number while your time()
(1 second is very big time for modern CPUs) give another seed.
There is no reason in simple app to call srand multiple times - this generator are weak by design and if you want real random numbers, you must use other (the best I know is Blum Blum Shub)
For me, there is no more or less random numbers - it always depends on seed, and they repeat if you use same seed. Using time is good solution because it's easy to implement, but you must use only one (at beginning of main()
) or when you sure that you calling srand(time(0))
in another second.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…