[SOLVED]MinGW 4.7.2 casting problems
I've recently upgraded my compilers to MinGW 4.7.2.
It's maybe a little harsh if I say that it doesn't know how to calculate any more, but I feel almost like that.
I'm aware that when calculating in binary there are some offsets and also in casting.
But the following is unacceptable in my opinion.
A few example of my outputs:
@// Note pow returns double
cout << (int)(pow(5, 3)) << endl; // prints: 124, correct: 125
cout << (int)(pow(10, 9)) << endl; // prints: 999 999 999, correct: 1 000 000 000
cout << (int)(52.4*pow(10, 1)) << endl; // prints: 523, correct: 524. If I get rid of pow works ok@
I've done tests on W7 x86 and x64 and on W8 x64, on 3 different processors. All the same.
It's also the same if I use pure C or if I use C++ static_cast<in> option.
MS C++ compiler works perfectly fine, as do older MinGW compilers.
Is someone experiencing similar issues or maybe knows a solution?
I'm using default settings and flags.
EDIT: Added missing closing parenthesis
This is related to how floating point values are stored and cast to other types
cout << (int)(pow(5, 3) << endl; // prints: 124, correct: 125
pow(5, 3) likely returns an approximation of 125 (124.9999999999999999999999999 to epsilon ).
When you cast to an integer it literally drops the decimal part of the value (no rounding).
For stuff like this I always add 0.5 to the result if I need an integer value so that I don't run into surprises. There are other methods to round if you need precision to something other than the nearest integer.
const int result = static_cast<int>(0.5 + pow(5, 3));
Note: You are missing a closing parenthesis in two of your examples. Your examples should print 'error' and not much else.
I'm aware of the that it returns x.9999....
But it was huge surprise to me cause it worked with previous version.
I like your solution.
Thanks for the note. I edited original post and added closing parenthesis. The first the examples weren't copy and paste.