If you call rand()
without first calling srand()
, it will act as if you have called srand(1)
implicitly. The relevant bit of the standard C99 7.20.2.2 The srand function
(on which cstdlib
is based) states:
If rand is called before any calls to srand have been made, the same sequence shall be generated as when srand is first called with a seed value of 1.
In other words, you will get the same sequence each time. You can change your main
into:
int main (int argc, char* argv []) {
srand (time (0)); // needs ctime header.
for (int i = 0; i < 5; i++)
cout << random (2, 5) << endl;
wait ();
}
to fix this, assuming you don't run it more than once a second.
As mentioned, you'll need the ctime
header for this. You should also be pulling in cstdlib
since that's where rand
and srand
live. It's also usually a good idea to use the cXXX
headers rather than the XXX.h
ones (cmath
rather than math.h
, for example).
So, having made all those changes (and using explicit namespaces, which I prefer though others may not), I'd end up with:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
void wait () {
int e;
std::cin >> e;
}
int random (int low, int high) {
if (low > high) return high;
return low + (std::rand() % (high - low + 1));
}
int main (int argc, char* argv []) {
std::srand (std::time (0));
for (int i = 0; i < 5; i++)
std::cout << random (2, 5) << '\n';
wait ();
}
which gives a different sequence each time I run it, for a few times anyway. Obviously, there's a hard limit on when the data will repeat (there are only 45 possibilities) and the "random" nature of the output means it may repeat before then as well :-)