问题
I have the following piece of code written in c++ and compiled by g++ 4.8.
double x = 0.123456789;
cout << x << endl;
I don't understand why I only get the output
0.1234567
even I define x as long double x
. It probably a quite naive question, but can any one give me some hits?
回答1:
Use the precision
function or the setprecision
manipulator to set the number of significant figures (or decimal places, if you also use fixed
).
cout.precision(10); // 10 significant figures
or
cout << setprecision(10); // also 10 significant figures
or
cout << fixed << setprecision(10); // always fixed-point format, 10 decimal places
By default, the precision is 6.
回答2:
This page has all you need, namely that you should use the std::setprecision
stream manipulator.
double x = 0.123456789;
std::cout << std::setprecision(10) << x << std::endl;
来源:https://stackoverflow.com/questions/27940723/how-to-change-control-the-output-precision-in-gcc-or-g