0

Who can explain me the differences? In both ways seems to act the same.

Piece 1

printf("The first randomly generated number: %d\n", rand()%100); 
srand(time(NULL));
printf ("The second randomly generated number: %d\n", rand()%100); 

Piece 2

printf("The first randomly generated number: %d\n", rand()%100); 
printf ("The second randomly generated number: %d\n", rand()%100); 
  • What do you get and what did you expect to have happen? Have you tried running these bits of code multiple times with a good bit of time between? [Time only ticks once a second, and a large number that is only a few digits different may not make that much of a difference as a seed]. – Mats Petersson Apr 10 '14 at 23:31
  • Put those statements in a loop and call them a few dozen times and you'll see the difference. If you don't use `srand`, the sequence of pseudorandom numbers `rand` returns will always be the same. – Carey Gregory Apr 10 '14 at 23:31
  • http://linux.die.net/man/3/rand – Keith Thompson Apr 10 '14 at 23:33
  • srand simply seeds the random number generator. It only needs to be called once in the entire program. If you don't seed the random number generator with something like the time then every time you run the program you get the same random numbers. – jodag Apr 10 '14 at 23:36
  • Thanks for all your answers! I did the loop test and I've seen the difference. – user3521512 Apr 10 '14 at 23:52

1 Answers1

0

The srand(time(NULL)); is used to seed the random number, but is sometimes cause problems. You can replace the NULL with an integer or number, like srand(time(1000));, because NULL means 0. NULL=0. The number you place is in milliseconds, so 1000 is 1 second. You need the srand(time(*something*));, or your program will sometimes not work. You can try it, if it doesn't work I will try to come up with something else. Hope it helps!