0

I am trying to generate a few random numbers in a C++ main program.

The solution I used was

#include <random>
#include <iostream>
#include <cmath>

using namespace std; 

// Function to generate a random double number between two limits
double getRandomDouble(double lower_bound,  double upper_bound)
{
   std::uniform_real_distribution<double> unif(lower_bound,upper_bound);
   std::default_random_engine re;
   double a_random_double = unif(re);

   return a_random_double ;
}

// Funtion to print a random number
void print()
{
  cout << getRandomDouble(0,10) << endl;
}

int main()
{
  for (int i=0; i<10; i++)
  {
    print();
  }
  return 0;
}

When I ran this program, I got the following output:

1.31538 1.31538 1.31538 1.31538 1.31538 1.31538 1.31538 1.31538 1.31538 1.31538

That is the same number printed 10 times.

How should I modify the code to get a different random number each time I call the function print()?

TaeNyFan
  • 109
  • 3
  • look at this question: https://stackoverflow.com/questions/34490599/c11-how-to-set-seed-using-random – RoQuOTriX Nov 05 '19 at 16:24
  • You initialize the random engine new every time you want to create a random number. This will produce always the first number of a random sequence. Initialize the engine only once, this will solve your problem. – Tinu Nov 05 '19 at 18:01
  • If you don't *seed* your generator it *will* return the same sequence every time. Always seed your generator and use a *good* seed. – Jesper Juhl Nov 05 '19 at 18:23

0 Answers0