The result of this cpp is 72.740, but the answer should be like 72.741
mx = 72.74050000;
printf("%.3lf \n", mx);
So I found the solution on website, and it told me to add "+1e-7" and it works
mx = 72.74050000;
printf("%.3lf \n", mx + 1e-7);
but I dont know the reason in this method, can anyone explain how it works?
And I also try to print it but nothing special happens…, and it turn out to be 72.7405
mx = 72.74050003;
cout << mx + 1e-10;
>Solution :
If you will output the value like
printf( "mx = %.16f\n", mx );
you will see
mx = 72.7404999999999973
So to make the result like 72.741 due to rounding in outputting with a call of printf you need to make the next digit equal to 5 instead of 4. It is enough to add 0.00001.
Here is a demonstration program.
#include <iostream>
#include <iomanip>
#include <cstdio>
int main( void )
{
double mx = 72.74050000;
printf( "mx = %.3f\n", mx + 0.00001);
std::cout << "mx = " << std::setprecision( 5 ) << mx + 0.00001 << '\n';
}
The program output is
mx = 72.741
mx = 72.741
0.00001 is the same as 1e-5.