Which fix removes the bug?
sum := 7 avg := sum / 2 fmt.Println(avg) // expected 3.5
- Write
avg := sum / 2.0 - Convert:
float64(sum) / 2 - Use
math.Round(sum / 2) - Declare
var avg float64first
Dividing two ints truncates. 2.0 is an untyped constant that becomes an int here, so it still prints 3; converting sum to float64 does real division.
Play Problem Solving ▸