Why does this average return 1.0 for []int{1, 2} instead of 1.5?
This average is meant to return the mean of a slice of ints as a float64, but for []int{1, 2} it returns 1.0 instead of 1.5.
func average(nums []int) float64 {
sum := 0
for _, n := range nums {
sum += n
}
return float64(sum / len(nums))
}
Identify the bug and explain the cause.
sum / len(nums) is integer division, which truncates toward zero before the float64(...) conversion — 3 / 2 is 1, then cast to 1.0. An empty slice also panics on divide-by-zero. Fix: convert first, float64(sum) / float64(len(nums)), and guard len(nums) == 0.
- ✗Converting to
float64after the division instead of before - ✗Forgetting integer division truncates toward zero rather than rounding
- ✗Not guarding
len(nums) == 0, which panics on divide-by-zero
- →Why does
float64(sum / len(nums))still truncate even though the result is a float? - →What value does
5 / 2produce in Go, and how does it differ from5.0 / 2?
Find the bug
func average(nums []int) float64 {
sum := 0
for _, n := range nums {
sum += n
}
return float64(sum / len(nums)) // BUG
}
Why 1.0, not 1.5
Inside float64(sum / len(nums)), sum / len(nums) is evaluated first. Both operands are int, so this is integer division: 3 / 2 truncates toward zero and gives 1. Only then does float64(1) convert the result to 1.0. The outer conversion is too late — the fractional part is already gone.
⚠️ On top of that, an empty slice makes len(nums) == 0, and the divide-by-zero panics with integer divide by zero.
✅ The fix is to convert to float64 before dividing and guard the empty case:
func average(nums []int) float64 {
if len(nums) == 0 {
return 0
}
sum := 0
for _, n := range nums {
sum += n
}
return float64(sum) / float64(len(nums)) // 1.5
}