You must seed the random number generator. see here for an example.
not-seeded.c
#include <stdio.h>
#include <stdlib.h>
int main ()
{
printf ("Random not seeded: %d\n", rand()%10);
return 0;
}
not-seeded output
Random not seeded: 3
Random not seeded: 3
Random not seeded: 3
Random not seeded: 3
Random not seeded: 3
seeded.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
srand(time(NULL));
printf ("Random seeded: %d\n", rand()%10);
return 0;
}
seeded output
Random fast seeded: 7
Random fast seeded: 7
Random fast seeded: 7
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 5
Random fast seeded: 5
Random fast seeded: 5
Random fast seeded: 5
fast-seeded.c
If you want to be able to call your utility more than once a second, you will have to use a different source for you seed, otherwise you will still end up with some repeated random numbers.
Here is an example that uses nanoseconds instead of time()
which only returns seconds.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
/* using nano-seconds instead of seconds */
srand((time_t)ts.tv_nsec);
printf ("Random fast seeded: %d\n", rand()%10);
return 0;
}
fast-seeded output
You can see here that the numbers aren't grouped as much as the previous example.
Random fast seeded: 9
Random fast seeded: 6
Random fast seeded: 5
Random fast seeded: 6
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 9
Random fast seeded: 4
Random fast seeded: 3
Random fast seeded: 2
uniformly distributed random numbers
If you are interested in uniformly distributed random numbers, you should see user3003631's answer below. If you are in fact using C++, that's how I would recommend doing random numbers. More information here too on this.