Take the following program:
#include <cstdlib>
using std::rand;
#include <iostream>
using std::cout;
int main()
{
cout << rand() << ' ' << rand() << ' ' << rand() << '\n';
}
Due to rand producing the same values as long as the seed isn’t changed using srand, this should produce three identical numbers.
e.g.
567 567 567
However, when I run this program it gives me three different values.
e.g.
6334 18467 41
When the program is (compiled and) run again, the same three numbers are generated. Shouldn’t I have to use srand to change the seed before I start getting different results from rand? Is this just my compiler/implementation trying to do me a favour?
OS: Windows XP
Compiler: GCC 4.6.2
Libraries: MinGW
EDIT:
By trying to use srand, I discovered that this is the result from a seed of 1 (which I guess is made default).
Each call to
rand()will always generate a different random number.The seed actually determines the sequence of random numbers that’s created. Using a different seed will get you another 3 random numbers, but you will always get those 3 numbers for a given seed.
If you want to have the same number multiple times just call
rand()once and save it in a variable.