So I've gotten the answer to my last question (I don't know why I didn't think of that). I was printing a double
using cout
that got rounded when I wasn't expecting it. How can I make cout
print a double
using full precision?
Thanks
So I've gotten the answer to my last question (I don't know why I didn't think of that). I was printing a double
using cout
that got rounded when I wasn't expecting it. How can I make cout
print a double
using full precision?
Thanks
Use std::setprecision:
std::cout << std::setprecision (15) << 3.14159265358979 << std::endl;
cout is an object that has a bunch of methods you can call to change the precision and formatting of printed stuff.
There's a setprecision(...) operation, but you can also set other things like print width, etc.
Look up cout in your IDE's reference.
You can set the precision directly on cout
and used the fixed
format specifier.
double d = 3.14159265358979;
cout.precision(15);
cout << "Pi: " << fixed << d << endl;
You can #include <limits>
to get the maximum precision of a float or double.
#include <limits>
typedef std::numeric_limits< double > dbl;
double d = 3.14159265358979;
cout.precision(dbl::digits10);
cout << "Pi: " << fixed << d << endl;
Most portably...
#include <limits>
using std::numeric_limits;
...
cout.precision(numeric_limits<double>::digits10 + 1);
cout << d;
Here is what I would use:
std::cout << std::setprecision (numeric_limits<double>::digits10 + 1)
<< 3.14159265358979
<< std::endl;
Basically the limits package has traits for all the build in types.
One of the traits for floating point numbers (float/double/long double) is the digits10 attribute. This defines the accuracy (I forget the exact terminology) of a floating point number in base 10.
See: http://www.cplusplus.com/reference/std/limits/numeric_limits.html
For details about other attributes.
With ostream::precision(int)
cout.precision( numeric_limits<double>::digits10 + 1);
cout << M_PI << ", " << M_E << endl;
will yield
3.141592653589793, 2.718281828459045
Why you have to say "+1" I have no clue, but the extra digit you get out of it is correct.
printf("%.12f", M_PI);
%.12f means floating point, with precision of 12 digits.