I don't understand the meaning of srand()
in <time.h>
to create a random number.
Here is my code:
/* srand example */
#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int main ()
{
printf ("First number: %d\n", rand()%100);
srand (time(NULL));
printf ("Random number: %d\n", rand()%100);
srand (1);
printf ("Again the first number: %d\n", rand()%100);
return 0;
}
and the results are:
First number: 41
Random number: 13
Again the first number: 41
Why is the result of srand(1)
different from srand(2)
?
Why does the result of srand(1)
or srand(2)
keep appearing again and again?
And why do I have to use srand(time(NULL))
in order to create a dynamic random number?