-2

This is a follow up question on an answer on this page:

How to generate random double numbers with high precision in C++?

#include <iostream>
#include <random>
#include <iomanip>    

int main()
{
    std::random_device rd;

    std::mt19937 e2(rd());

   std::uniform_real_distribution<> dist(1, 10);

   for( int i = 0 ; i < 10; ++i )
   {
      std::cout << std::fixed << std::setprecision(10) << dist(e2) << std::endl ;
   }

  return 0 ;
}

The answer works fine but I had a hard time to realize how to put the output of this code in a double variable instead of printing it to stdout. Can anyone help with this?

Thanks.

Community
  • 1
  • 1

1 Answers1

3

You're getting confused between actual precision and displayed precision - try this:

#include <iostream>
#include <random>
#include <iomanip>    

int main()
{
    std::random_device rd;
    std::mt19937 e2(rd());
    std::uniform_real_distribution<> dist(1, 10);

    double v = dist(e2);   // get a random double at full precision

    std::cout << std::fixed << std::setprecision(10) << v << std::endl;
                           // display random double with 10 digits of precision
    return 0;
}
Paul R
  • 208,748
  • 37
  • 389
  • 560