Reputation: 4954
The following code in C++:
double x = 500000.6;
printf("%f\n", x);
cout << x << endl;
prints the following:
500000.600000
500001
Why cout
isn't printing the correct value (500000.6)?
Putting the following line as the beginning of the code makes cout
prints correct result:
cout.precision(7);
However, setting the precision to 6 (which is the default anyways) doesn't print the expected result.
Why this happen? I have only 1 digit after the decimal point, not 7 digits!
Upvotes: 1
Views: 56
Reputation: 87957
By default, the precision is the total number of significant digits. It's not the number of digits after the decimal point. 500000.6
has seven significant digits, 500001
has only six.
Try this instead
cout << fixed << setprecision(1) << x << endl;
When used for fixed format, the precision is the number of digits after the decimal point.
Upvotes: 1