Next: Division and Remainder, Previous: Integer Overflow, Up: Arithmetic [Contents][Index]
Mixing integers and floating-point numbers in a basic arithmetic operation converts the integers automatically to floating point. In most cases, this gives exactly the desired results. But sometimes it matters precisely where the conversion occurs.
j are integers,
(i + j) * 2.0 adds them
as an integer, then converts the sum to floating point for the
multiplication. If the addition gets an overflow, that is not
equivalent to converting both integers to floating point and then
adding them. You can get the latter result by explicitly converting
the integers, as in
((double) i + (double) j) * 2.0.
See Explicit Type Conversion.
Adding or multiplying several values, including some integers and some
floating point, does the operations left to right. Thus,
i + j converts
i to floating point, then adds 3.0, then
j to floating point and adds that. You can specify a
different order using parentheses:
3.0 + (i + j) adds
j first and then adds that result (converting to floating
point) to 3.0. In this respect, C differs from other languages, such