Expand|Select|Wrap|Line Numbers
- /* floor example */
- #include <iostream>
- #include <math.h>
- int main ()
- {
- float a=10.0f;
- float b=0.9f;
- float c=a*b;
- float d=floor(c);
- std::cout << "floor of " << c << " is " << d << std::endl;
- return 0;
- }
floor of 9 is 8
The second program is
Expand|Select|Wrap|Line Numbers
- /* floor example */
- #include <iostream>
- #include <math.h>
- int main ()
- {
- float a=10.0f;
- float b=0.9f;
- float c=a*b;
- std::cout << ""; //inserted line of executable code
- float d=floor(c);
- std::cout << "floor of " << c << " is " << d << std::endl;
- return 0;
- }
floor of 9 is 9
I am using MSVC++ 6.0 on an XP workstation. (SP2 for XP, and SP6 for VC++) I understand how floating point numbers are represented in the computer. I also know that the representation of c in the first program is 8.999... and in the second program the representation is 9.000. I think that due to compiler optimizations, the value of c in the first program is not being rounded correctly and stored, but the register containg the result of a*b is being used directly without rounding. In the second program the inserted line of executable code seems to cause the value stored in c to be correctly rounded.
Is this a bug in the compiler, and if so is there a fix?