c++ - same number is displayed for a single output but the output is as expected when there is more than 1 output -
this small program:
#include <iostream> #include <cstdlib> using namespace std; int main() { long x = rand(); cout << x << endl; }
it displays 41
.but if modify program ,
#include <iostream> #include <cstdlib> using namespace std; int main() { for( int = 0 ; <= 9 ; i++ ) { long x = rand(); cout << x << endl; } }
the output expected.the set of random numbers. output:
41
18467
6334
26500
19169
15724
11478
29358
26962
24464
but why same number when run first program how rand
function ?
the random number generator built in compilers pseudo random number generator. typically use recursive equation generate next random number , use seed generate first random number. check link.
to avoid having same random number first one, need change seed. again, same seed give same initial random number same random number sequence. should change seed every time run program/thread.
to set seed, need call srand(). best way change seed value every time srand()
called use current timestamp: time(0)
.
Comments
Post a Comment