< previous page page_97 next page >

Page 97
someFloat = float(3 * someInt + 2);
someInt = int(5.2 / someFloat - anotherFloat);
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif 3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
Type Coercion The implicit (automatic) conversion of a value from one data type to another.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif 3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
Type Casting The explicit conversion of a value from one data type to another; also called type conversion.
Both of the statements
someInt = someFloat + 8.2;
someInt = int(someFloat + 8.2);
produce identical results. The only difference is in clarity. With the cast operation, it is perfectly clear to the programmer and to others reading the program that the mixing of types is intentional, not an oversight. Countless errors have resulted from unintentional mixing of types.
Note that there is a nice way to round off rather than truncate a floating point value before storing it into an int variable. Here is the way to do it:
someInt = int(someFloat + 0.5);
With pencil and paper, see for yourself what gets stored into someInt when someFloat contains 4.7. Now try it again, assuming someFloat contains 4.2. (This technique of rounding by adding 0.5 assumes that someFloat is a positive number.)
Arithmetic Expressions
So far we have been talking about mixing data types across the assignment operator (=). It's also possible to mix data types within an expression:
someInt * someFloat
4.8 + someInt - 3
Such expressions are called mixed type (or mixed mode) expressions.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif 3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
Mixed Type Expression An arithmetic expression that contains operands of different data types; also called mixed mode expression.

 
< previous page page_97 next page >