Page excerpted from Expressions topic of a first year course in Structured Programming

Conversions

ints and doubles are different types. Computers can

They can't do mixed arithmetic. Instead, they convert from one type to the other.

In the example evaluation of the term 2 * x requires an implicit conversion.

The 2 is automatically converted to a double yielding 2.0 * x and then a double multiply is called.

 

Exercises

What will the following functions return (and what conversions will be carried out inside them)?

  1. int fee() {
      return (11/6+11%6);
    }
  2. int fi() {
      return (1.1 + 10.0/5);
    }
  3. double fo() {
      return (3 * 6 – 12.0 / 5 + 4);
    }

No conversions—all operations are integer. 11/6 = 1 & 11%6 = 5 so 6 is returned.

5 is converted to 5.0,       10.0/5.0 = 2.0    1.1 + 2.0 = 3.1    converted to int for return so 3 is returned.

5 is converted to 5.0,       12.0/5.0 = 2.4    3 * 6 = 18     18 and 4 are converted to double18.0 and 4.0—for summation with 2.4 yielding 19.6 which is the double returned.

 

Examples Shown in Full