Double print with a given accuracy, rounded in a given direction

Note. I know that there are some similar questions, but I could not find the answer to what I ask here.

I want to print a double in std :: ostream, rounded to the side + oo or -oo with n decimal places.

Multiplying by 10 ^ n, gender or overlapping, and then multiplying the result by 10 ^ -n is not an option, as the result may not be presented.

So far, I have been as follows:

#include <iostream> #include <cfenv> int main() { double one_third = 1.0/3.0; std::cout.precision(4); fesetround(FE_DOWNWARD); std::cout << one_third << std::endl; fesetround(FE_UPWARD); std::cout << one_third << std::endl; } 

The output with gcc-4.7.2 is as follows:

 0.3333 0.3333 

I expected:

 0.3333 0.3334 

So what is wrong with this code?

Thanks!

+4
source share
1 answer

EDIT: This is a GCC 4.7.2 bug. The code works fine in GCC 4.8.1, but does not execute in 4.7.2.

This code ( example on ideone.com ) works fine with GCC 4.8.1:

 #include <iostream> #include <cfenv> int main() { double one_third = 1.0/3.0; std::cout.precision(4); std::fesetround(FE_DOWNWARD); std::cout << one_third << std::endl; std::fesetround(FE_UPWARD); std::cout << one_third << std::endl; return (0); } 

Program output:

 0.3333 0.3334 
+3
source

Source: https://habr.com/ru/post/1501856/


All Articles