//This program illustrates why you should not compare floating point numbers for equality //It also how how to do so safely #include #include #include using namespace std; int main() { float k = 0; cout << setprecision(8); //Notice that k never hits 1000.0 exactly! //If you change the test to ask for equality, you will get an endless loop! while (k <= 1000.0) { k+=0.01; //display the last few iterations if (k > 999.9) { cout << fixed <"Last few iterations\n"; cout << "k is " << k << "\t"; } } //Now let's test if three floating point sides of a triangle form a right triangle double a = 3.00000000001, b = 4.0000000002, c; c = sqrt(a*a + b*b); //compute the hypotenuse and test for equality according to the Pythagorean theorem cout << "\n\nTesting for strict equality\n"; if (a*a + b*b == c*c) { cout << "Sides a = " << a << " b = " << b << " and c = " << c << "\nform a right triangle\n"; } else { cout << "Sides a = " << a << " b = " << b << " and c = " << c << "\ndo not form a right triangle\n"; } //Now test within a tolerance level of equality cout << "\n\nTesting for equality using a tolerance\n"; if (abs(a*a + b*b - c*c) <= 1E-8 ) cout << "Sides a = " << a << " b = " << b << " and c = " << c << "\nform a right triangle\n"; else cout << "ides a = " << a << " b = " << b << " and c = " << c << "\ndo not form a right triangle\n"; return 0; }