Reputation: 473
I have this following code:
#include <iostream>
#include <cstdlib>
#include <ctime>
int getRandomNumber(int min,int max)
{
static const double fraction = 1.0/(static_cast<double>(RAND_MAX)+1.0);
return static_cast<int>(rand()*fraction*(max-min+1)+min);
}
int main()
{
srand(static_cast<int>(time(0)));
std::cout<<getRandomNumber(1,6);
return 0;
}
If I run this program in succesions, then i get the same number. But when i run this one with cout statement as:
std::cout<<getRandomNumber(1,6)<<getRandomNumber(1,6);
I get different numbers every time. So how is this possible?? Am I missing something?
Upvotes: 0
Views: 95
Reputation: 21
When using function time() as seed and running program within short interval, the first result of rand() will be changed in a very small number comparing to RAND_MAX.
This explained why you got the same number, when using fraction to get a number from 1 - 6.
Here is another way to get random number from 1 to 6, which may do better.
rand() % 6 + 1
Upvotes: 0
Reputation: 48605
The time()
function returns time in seconds so running the program two or more times within the same second will cause the random number system to be seeded with exactly the same number.
Upvotes: 2