mardi 5 novembre 2019

Random number generator returning same value everytime

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()?




Aucun commentaire:

Enregistrer un commentaire