|
|
|
|
|
|
|
Of course, we have to be careful about the data types of things we compare. The safest approach is always to compare ints with ints, floats with floats, and chars with chars. If you mix data types in a comparison, implicit type coercion takes place just as in arithmetic expressions. If an int value and a float value are compared, the computer temporarily coerces the int value to its float equivalent before making the comparison. As with arithmetic expressions, it's wise to use explicit type casting to make your intentions known: |
|
|
|
|
|
|
|
|
someFloat >= float(someInt) |
|
|
|
|
|
|
|
|
Until you learn more about the char type in Chapter 10, be careful to compare char values only with other char values. For example, the comparisons |
|
|
|
|
|
|
|
|
generates an implicit type coercion and a result that probably isn't what you expect. |
|
|
|
|
|
|
|
|
We can use relational operators not only to compare variables or constants, but also to compare the values of arithmetic expressions. In the following table, we compare the results of adding 3 to x and multiplying y by 10 for different values of x and y: |
|
|
|
|
| Value of x | Value of y | Expression | Result |  |
|
|
|
|
12 |
|
|
|
| | x + 3 <= y * 10 | 1 (TRUE) |  |
|
|
|
|
20 |
|
|
|
| | x + 3 <= y * 10 | 1 (FALSE) |  |
|
|
|
|
7 |
|
|
|
| | x + 3 != y * 10 | 0 (FALSE) |  |
|
|
|
|
17 |
|
|
|
| | x + 3 == y * 10 | 1 (TRUE) |  |
|
|
|
|
100 |
|
|
|
| | x + 3 > y * 10 | 1 (TRUE) |
|
|
|