Possible Duplicate:
why do i always get the same sequence of random numbers with rand() ?
This is my file so far:
#include <stdio.h>
int main(void) {
int y;
y = generateRandomNumber();
printf("\nThe number is: %d\n", y);
return 0;
}
int generateRandomNumber(void) {
int x;
x = rand();
return x;
}
My problem is rand() ALWAYS returns 41. I am using gcc on win... not sure what to do here.
EDIT: Using time to generate a random number won't work. It provides me a number (12000ish) and every time I call it is just a little higher (about +3 per second). This isn't the randomness I need. What do I do?
you need to provide it a seed.
From the internet -
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int i, stime;
long ltime;
/* get the current calendar time */
ltime = time(NULL);
stime = (unsigned) ltime/2;
srand(stime);
for(i=0; i<10; i++) printf("%d ", rand());
return 0;
}
Standard trick is:
srand(time(0)); // Initialize random number generator.
NOTE: that function is srand
, not rand
.
Do this once in your main
function. After that, only call rand
to get numbers.
Depending on the implementation, it can also help to get and discard a few results from rand
, to allow the sequence to diverge from the seed value.
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