#include <stdio.h> #include <stdlib.h> /* Puzzle B01 -- print N random integers */ int main(int argc, char *argv[]) { int j; int limit = 25; unsigned int seed = 132; /* Use command line parameters if supplied */ if ( argc == 3 ) { limit = atoi( argv[1] ); seed = atoi( argv[2] ); } /* Initialize the random number generator */ srand( seed ); for ( j=0; j < limit; j++ ) { printf("%5d\n", rand() ); } printf("\n"); system("pause"); return 0; }
Comments:
Without initialization,
rand()
generates the same sequence of
integers each time the program is run.
To get a different sequence of integers,
initialize rand()
:
srand( seed )
The seed
is an unsigned int
. Every timerand()
is initialized with the same seed, it will generate the same sequence of integers.
Another way to initialize the generator is:
srand( time(NULL) )
This method uses the function time(NULL)
which returns
the number of elapsed seconds since January first, 1970.
This will be a different number each time the program is run,
so rand()
will be initialized differently each time,
and each run of the program will use a different sequence of
random integers.