Explain why it is more difficult to compare floating-point numbers than integers.Write C++ code to test whether an integer n equals 10 and whether a floating-pointnumber x equals 10
R3.5 Explain why it is more difficult to compare floating-point numbers than integers. Write C++ code to test whether an integer n equals 10 and whether a floating-point number x equals 10.
Step By Step Solution
Step 1 of 4
Comparing two integers is very easy. Integer comparison is well defined and works on any integer value. However, even an operation seemingly as simple as comparing two floating-point numbers can cause trouble.
Floating-point numbers only have limited precision so it’s very likely that any mathematical operation (like addition, multiplication, etc.) will introduce small errors into the result. Also due to rounding errors, most floating point numbers end up being slightly imprecise. As long as this imprecision stays small, it can usually be ignored. However, it also means that numbers expected to be equal (e.g. when calculating the same result through different correct methods) often differ slightly, and a simple equality test fails. For example: