-
random numbers
I have a random number function and when i call it in another function two different times how come it is always the same number.
The rand function looks like this
Code:
int getRand(int i)
{
srand(time(NULL));
return (rand()%i)+1;
}
If i call it twice for example
Code:
num1 = getRand(9);
num2 = getRand(9);
It always prints different values when the program runs but it prints the same value each time for both numbers. How come?
-
You should call srand() only once in your program.
Some reading for you
-
Heraclitus
The reason for the numbers being the same, if I am not mistaken, is due to the fact that srand(time(NULL)) will set the random seed using the system time (in seconds). As you are calling it twice in quick succession, these two function calls will almost certainly use the same seed to produce a psuedo-random number (The "psuedo" part is why your numbers are always the same). If you pause the program for more than a second between each call, the numbers will be different... Or at least, a 1 - (1/i * 1/i) chance of being different. ;)
But anyway, you just need to use srand(time(NULL)) once to set a decent seed.
-
srand() should be used only once in your program, delele him from the function, and add him at the top of main(), this is just a suggestion.
-
No No No.... you're all wrong. The answer is you only need to call srand() once in your program. :rolleyes:
Now, please, lets not repeat the same answer any more :mad: