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

I

Intaek LIM

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;
}
 
A

Andreas Kahari

Intaek LIM wrote: said:
// seed is the return value for time(0)
// i wrote it by my hand. :-(
int seed = 1067589554;
srand(seed);

The time() function returns a value that represents the current
time. Seeding the pseudo random generator with time(0) will
ensures that you get a different pseudo random list of numbers
each time you run the program.

Hard coding the seed ("1067589554" in your code) ensures that
you get the *same* pseudo random list of numbers each time you
run your program.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top