Possible Duplicate:
Generating random numbers in C
using rand to generate a random numbers
I'm trying to generate random numbers but i'm constantly getting the number 41.
What might be going so wrong in such a simple snippet?
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int a = rand();
printf("%d",a);
return 0;
}
Thanks for help.
You need to give a different seed, for example:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int a;
srand ( time(NULL) );
a = rand();
printf("%d",a);
return 0;
}
You need to seed the generator.
This is expected. The reason is for repeatability of results. Let's say your doing some testing using a random sequence and your tests fails after a particular amount of time or iterations. If you save the seed, you can repeat the test to duplicate/debug. Seed with the current time from epoch in milliseconds and you get randoms as you expect ( and save the seed if you think you need to repeat results ).