rand()

I used rand()function in the following code but in every time running of my program I took same results. why? it's strange for me because this function must produce random numbers...!!!

#include <iostream>
using namespace std;
int main()
{
for(int i = 0; i <= 11; i++)
cout << rand() << endl;
cin.get();
return 0;
}
Last edited on
The numbers aren't actually random -- they're generated by a formula, so they're just pseudorandom.

Anyways, you need to seed the random number generator (with a different number each time you run your program) or you'll get the same numbers every time.
The easiest way to do that is to #include <cstdlib> (you should have already been doing that, since rand isn't guaranteed to be in <iostream>) and #include <ctime> and then put srand(time(0)); at the very beginning of main.
In some cases having the same results each time lets you know what to expect if something unexpected is happening and you don't want a list of consecutive numbers as a test list. If you seed with the same number you get a different set of numbers yet the same on each run.
seeding the generator with the clock will give you a different time stamp for each run.
You can mix it up a bit by masking your rand() with a previously generated set of numbers or multiplying a rand result with a rand result. etc.
Topic archived. No new replies allowed.