Possible Duplicates:
Incorrect floating point math?
Float compile-time calculation not happening?
Strange stuff going on today, I’m about to lose it…
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
cout << setprecision(14);
cout << (1/9+1/9+4/9) << endl;
}
This code outputs 0 on MSVC 9.0 x64 and x86 and on GCC 4.4 x64 and x86 (default options and strict math…). And as far as I remember, 1/9+1/9+4/9 = 6/9 = 2/3 != 0
1/9is zero, because 1 and 9 are integers and divided by integer division. The same applies to4/9.If you want to express floating-point division through arithmetic literals, you have to either use floating-point literals
1.0/9 + 1.0/9 + 4.0/9(or1/9. + 1/9. + 4/9.or1.f/9 + 1.f/9 + 4.f/9) or explicitly cast one operand to the desired floating-point type(double) 1/9 + (double) 1/9 + (double) 4/9.P.S. Finally my chance to answer this question 🙂