pass time(0) to srand() when generating random numbers.

From: Intaek LIM (litnsio2_at_nownuri.net)
Date: 10/31/03


Date: 31 Oct 2003 00:45:34 -0800

generally, we use srand(time(0)) to generate random numbers.
i know why we use time(0), but i can not explain how it operates.

first, see example source below.

---------------------------------------------
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
   printf("This will generate 5 random numbers.\n\n");
    
   srand(time(0));
   
   int i;
   for(i=0; i<5; i++)
   {
      printf("generated %d\n", rand());
   }
   
   return 0;
}
---------------------------------------------

this is an idiom of generating random numbers, i think.
and a different source below operates correctly too.

---------------------------------------------
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
   printf("This will generate 5 random numbers.\n\n");
   
   int seed = time(0);
   srand(seed);
   
   int i;
   for(i=0; i<5; i++)
   {
      printf("generated %d\n", rand());
   }
   
   return 0;
}
---------------------------------------------

but, following source produces incorrect results.
(returns the same values everytime)

---------------------------------------------
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
   printf("This will generate 5 random numbers.\n\n");
   
   // seed is the return value for time(0)
   // i wrote it by my hand. :-(
   int seed = 1067589554;
   srand(seed);
   
   int i;
   for(i=0; i<5; i++)
   {
      printf("generated %d\n", rand());
   }
   
   return 0;
}
---------------------------------------------

what is the difference of these three sources?
plz tell me something who knows it.



Relevant Pages