C++ question here, using Code::Blocks. I'm trying to run this code to test the pseudo-random function
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int count = 0;
while (count < 10){
srand(time(NULL));
cout << rand() << ' ';
cout << (time( NULL )) << " \n";
count++;
}
return 0;
}
The output from this is 10 equal lines. This is not really the problem, as the seed here is the same, so the result should be the same. The problem is that if I run this program again it gives 10 very similar lines with little variation not only on the time() output, but on the rand output too.
The srand(time(NULL)) is giving very similar answers that are basically the same return value, only a little bigger.
(Returning 9631 on first run, and then 9656 on the second).
My question is, is that the expected behavior? And how can I get more different results like 38 on the first run, and 671 on the second?
To make a random number with a nearly the same seed(time), you can add a static variable to make rand()
behaves different even with same parameter; or, you can make the parameter change when you get same time. For example:
int t=0;
...
rand(t=(t*7)^time(NULL));