I ran into an issue when trying to generate random numbers where it outputs an ascending sequence of numbers with increments of 3 every second. I am using mingw g++ 6.3.0 with the following compiler flags: -std=c++11 -Wall.
As an example, after running the following code and running the executable multiple times it provides the following output below:
main.cpp:
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
std::srand(std::time(0));
int rnd = std::rand();
std::cout << rnd << '\n';
return 0;
}
Console output:
C:\...>make
g++ main.cpp -std=c++11 -Wall -o a.exe
C:\...>a
21154
C:\...>a
21157
C:\...>a
21157
C:\...>a
21157
C:\...>a
21160
C:\...>a
21160
C:\...>a
21163
C:\...>a
21163
>Solution :
Well, rand() will return the same sequence of numbers for a given seed, which is why you see the change every second (you’re seeding it with the time in seconds).
As for incrementing by 3 each time, std::rand is not guaranteed to produce sequences of any particular quality, and yours appears particularly not-that-great (not uncommon for rand). There are better quality generators in <random> (see docs here).