Gimpel
When I was in class here at Full Sail University, I was introduced to a nice little site called Gimpel.com. What this is for is pretty much to promote lint software, which is something used to find little bugs in your program you may not even realize. Something interesting they do have on the site is a little section called bug of the month, where they post some of the problems, as well as reasons and possibly even solutions for said problems. Here I'll be showing and explaining some of these same problems, but in a little different way.
bug777.cpp - January 1999
1 #include <iostream.h>
2
3 int main()
4 {
5 const double three = 3.0;
6 double x, y, z;
7 x = 1 / three;
8 y = 4 / three;
9 z = 5 / three;
10 if( x + y == z )
11 cout << "1/3 + 4/3 == 5/3 \n";
12 else
13 cout << "1/3 + 4/3 != 5/3 \n";
14 return 0;
15 }
Can you find the problem?
Answer :: line 10
It will go into the else just because of how floating point works. One possible solution would be to type cast as an int, but that is not very accurate, a better way would be to use these doubles, but cast them as floats. For example if ( float(x + y) == (float)z) since your dropped a great deal of the extra precision, your loosing a great deal of these trailing digits, and you have a rough equivalency which will actually be equal even if they aren't exactly 5/3. no computer can be exact with a number like 5/3 just because it repeats forever.