< previous page page_201 next page >

Page 201
(text box continued from previous page)
(FALSE). The computer then compares this 1 or 0 with the number 24. Because both 1 and 0 are less than 24, the result is always TRUE. To write this expression correctly in C++, use the && operator:
12 < y && y < 24

Relational Operators with Floating Point Types
The relational operators can be applied to any of the three basic data types: int, float, and char. We've talked about comparing int and char values. Here we look at float values.
Do not compare floating point numbers for equality. Because small errors in the rightmost decimal places are likely to arise when calculations are performed on floating point numbers, two float values rarely are exactly equal. For example, consider the following code that uses two float variables named oneThird and x:
oneThird = 1.0 / 3.0;
x = oneThird + oneThird + oneThird;
We would expect x to contain the value 1.0, but it probably doesn't. The first assignment statement stores an approximation of 1/3 into oneThird, perhaps 0.333333. The second statement stores a value like 0.999999 into x. If we now ask the computer to compare x with 1.0, the comparison yields FALSE.
Instead of testing floating point numbers for equality, we test for near equality. To do so, we compute the difference between the two numbers and test to see if the result is less than some maximum allowable difference. For example, we often use comparisons like this:
fabs(r - s) < 0.00001
where fabs is the floating point absolute value function from the C++ standard library. The expression fabs(r - s) computes the absolute value of the difference between two float variables r and s. If the difference is less than 0.00001, the two numbers are close enough to call them equal. We discuss this problem with floating point accuracy in more detail in Chapter 10.

 
< previous page page_201 next page >