|
|
|
|
|
|
|
Whenever an integer value and a floating point value are joined by an operator, implicit type coercion occurs as follows. |
|
|
|
|
|
|
|
|
1. The integer value is temporarily coerced to a floating point value. |
|
|
|
|
|
|
|
|
2. The operation is performed. |
|
|
|
|
|
|
|
|
3. The result is a floating point value. |
|
|
|
|
|
|
|
|
Let's examine how the machine evaluates the expression 4.8 + someInt - 3, where someInt contains the value 2. First, the operands of the + operator have mixed types, so the value of someInt is coerced to 2.0. (This conversion is only temporary; it does not affect the value that is stored in someInt.) The addition takes place, yielding a value of 6.8. Next, the subtraction (-) operator joins a floating point value (6.8) and an integer value (3). The value 3 is coerced to 3.0, the subtraction takes place, and the result is the floating point value 3.8. |
|
|
|
|
|
|
|
|
Just as with assignment statements, you can use explicit type casts within expressions to lessen the risk of errors. Writing expressions like |
|
|
|
|
|
|
|
|
float(someInt) * someFloat
4.8 + float(someInt - 3) |
|
|
|
|
|
|
|
|
makes it clear what your intentions are. |
|
|
|
|
|
|
|
|
Not only are explicit type casts valuable for program clarity, they also can be mandatory for correct programming. Given the declarations |
|
|
|
|
|
|
|
|
int sum;
int count;
float average; |
|
|
|
|
|
|
|
|
suppose that sum and count currently contain 60 and 80, respectively. If sum represents the sum of a group of integer values and count represents the number of values, let's find the average value: |
|
|
|
|
|
|
|
|
average = sum / count; // Wrong |
|
|
|
|
|
|
|
|
Unfortunately, this statement stores the value 0.0 into average. Here's why. The expression to the right of the assignment operator is not a mixed type expression. Both operands of the / operator are of type int, so integer division is performed. 60 divided by 80 yields the integer value 0. Next, the machine implicitly coerces 0 to the value 0.0 before storing it into average. The way to find the average correctly, as well as clearly, is this: |
|
|
|
|
|
|
|
|
average = float(sum) / float(count); |
|
|
|
|
|