My assignment involve printing out double numbers with 2 digits after the decimal point. In one of the example tests, I got the output is 78.125. My teacher taught me to use the setprecision function to print out the number
#include <iomanip>
...some code
cout << fixed << setprecision(2);
cout << x /*the number*/
Normally this would do just fine. However the example output is 78.13 while the output of my code is 78.12. I can't figure out anyway to do this.
The rounding behaviour of std::cout
and std::setprecision
is implementation defined .
C++11 clears up this mess by supplying a function called std::fesetround
which you can call using
std::fesetround(FE_TONEAREST);
before your std::cout
statement. See http://en.cppreference.com/w/cpp/numeric/fenv/feround for more details.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.