This is a small program:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
long x = rand();
cout << x << endl;
}
It always displays 41.But if i modify the program like ,
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
for( int i = 0 ; i <= 9 ; i++ ) {
long x = rand();
cout << x << endl;
}
}
The output is as expected.The set of random numbers.
OUTPUT:
41
18467
6334
26500
19169
15724
11478
29358
26962
24464
But why i get the same number when i run first program How does rand actually function ?
The random number generator built in compilers are usually pseudo random number generator. They typically use a recursive equation to generate next random number and use a seed to generate first random number. Check this link.
To avoid having same random number as the first one, you need to change the seed. Again, same seed will give you same initial random number as well as same random number sequence. So you should change the seed every time you run your program/thread.
To set the seed, you need to call srand(). The best way to change the seed value every time
srand()is called is to use current timestamp:time(0).