Chapter 3 Page 55 Mini Exercises (3)
It says “Correct the mistake in the above exercise by casting age1 and age2 to Double in the formula”, how can I do it IN the formula?
This is the formula: (age1 + age2) / 2
Thanks
Chapter 3 Page 55 Mini Exercises (3)
It says “Correct the mistake in the above exercise by casting age1 and age2 to Double in the formula”, how can I do it IN the formula?
This is the formula: (age1 + age2) / 2
Thanks
In the original formula:
let avg1 = (age1 + age2) / 2
Both operands of / are integers so the operation is an integer division and the result is truncated.
If you cast both age1 and age2 to Double like this:
let avg2 = (Double(age1) + Double(age2)) / 2
The first operand of / is now a Double. Because of this, 2 is inferred to be a Double as well and the result is correct now.