gcc 4.4.4 c89
I am using the code below. However, I keep getting the same number:
size_t i = 0;
for(i = 0; i < 3; i++) {
/* Initialize random number */
srand((unsigned int)time(NULL));
/* Added random number (simulate seconds) */
add((rand() % 30) + 1);
}
I would like to get 0 to 30 returned. However, the last time I ran this I got 17 three times.
Many thanks,
Explanation : rand() generate random number between the wide range of 0 to RAND_MAX.
However, Excel uses what is called a pseudorandom number generator, in this case, the Mersenne Twister algorithm. What that means is that, technically speaking, the numbers that Excel's RAND functions generate aren't truly random.
You're seeding inside the loop (with the same value because of how quickly the loop will be executed), which causes the random number generated to be the same each time.
You need to move your seed function outside the loop:
/* Initialize random number */
srand((unsigned int)time(NULL));
for(i = 0; i < 3; i++) {
/* Added random number (simulate seconds) */
add((rand() % 30) + 1);
}
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