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.
However, the numbers generated by the rand() are not random because it generates the same sequence each time the code executed.
rand() returns a pseudo-random number in the range of [0, RAND_MAX).
The rand() function in C++ is used to generate random numbers; it will generate the same number every time we run the program. In order to seed the rand() function, srand(unsigned int seed) is used. The srand() function sets the initial point for generating the pseudo-random numbers.
The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX. RAND_MAX is a constant whose default value may vary between implementations but it is granted to be at least 32767.
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 ).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With