"random" (line 9) is a different variable than "random" (line 22).
The line 9 variable is global, so it is automatically initialized to zero.
Call
srand() only once, at the beginning of main.
Better yet, avoid
rand().
(C++ is somewhat obnoxious because you must code a lot of boilerplate to use random stuff, but it is significantly better.)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#include <chrono>
#include <random>
std::mt19937& rng()
{
auto seed = std::chrono::system_clock::now().time_since_epoch().count();
static std::mt19937 g( seed );
return g;
}
double random( double min, double max )
{
std::uniform_real_distribution <double> d( min, max );
return d( rng() );
}
#include <iostream>
using namespace std;
int main()
{
cout << "Random number 1: " << random( 1, 50 ) << "\n";
cout << "Random number 2: " << random( 1, 50 ) << "\n";
}
|
Also, please realize that a
floating point random number range is different than an integer range.
If you were to use a
std::uniform_int_distribution you would get a number in [min,max].
But with a
std::uniform_real_distribution you'll get a number in [min,max).
It's a subtle difference, but in practice it depends on what kind of data you really need.
Hope this helps.