Reputation: 733
Note: I know there are some similar questions but I couldn't find the answer to what I'm asking here.
I want to print a double to a std::ostream rounded towards +oo or -oo with n decimal places.
Multiplying by 10^n, floor'ing or ceil'ing, and then multiplying the result by 10^-n is not an option, since the result might not be representable.
What I have so far is the following:
#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 the following:
0.3333
0.3333
I was expecting:
0.3333
0.3334
So what is wrong with this code?
Thanks!
Upvotes: 4
Views: 193
Reputation: 3918
EDIT: This must be a GCC 4.7.2 bug. The code works fine in GCC 4.8.1, but fails in 4.7.2.
This code (example on ideone.com) works just 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
Upvotes: 3