As you learned in the chapter, you must be careful when comparing two real numbers for either

Question:

As you learned in the chapter, you must be careful when comparing two real numbers for either equality or inequality because some real numbers cannot be stored precisely in memory. To determine whether two real numbers are either equal or unequal, you should test that the difference between both numbers is less than some acceptable small value, such as 0.00001. 

a. Start your C++ development tool, and view the Advanced16.cpp file. The file is contained in either the Cpp8\Chap05\Advanced16 Project folder or the Cpp8\Chap05 folder. (Depending on your C++ development tool, you may need to open this exercise’s solution/project file first.) The code divides the contents of the num1 variable (10.0) by the contents of the num2 variable (3.0), storing the result (approximately 3.33333) in the quotient variable. An if statement is used to compare the contents of the quotient variable with the number 3.33333. The if statement displays a message that indicates whether the numbers are equal. 

b. Run the program. Even though the message on the screen states that the quotient is 3.33333, the message indicates that this value is not equal to 3.33333. Close the Command Prompt window. 

c. If you need to compare two real numbers for equality or inequality, first find the difference between both numbers, and then compare the absolute value of that difference to a small number, such as 0.00001. The absolute value of a number is a positive number that represents the distance the number is from 0 on the number line. For example, the absolute value of the number 5 is 5, and so is the absolute value of the number –5; both numbers are an equal distance from 0 on the number line. You can use the C++ fabs function to find the absolute value of a real number; however, your program must contain the #include  directive. Modify the program appropriately. Save and then run the program. This time, the message “Yes, the quotient 3.33333 is equal to 3.33333.” appears.

Fantastic news! We've Found the answer you've been seeking!

Step by Step Answer:

Question Posted: