TryBugHunt
rustType errorEasy

Average of 2 and 3 comes out as 2.0

BugFind the bug and fix the code

What it should do

average(scores) returns the mean of a list of scores as a decimal number. Example: average(&[2, 3]) → 2.5

What happens instead

average(&[2, 3]) returns 2.0 instead of 2.5.

fn average(scores: &[i32]) -> f64 {
    let total: i32 = scores.iter().sum();
    (total / scores.len() as i32) as f64
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the type errors pattern

Integer overflow, truncating casts with as, and types that do not convert the way you expect.

What you'll practise

An easy Rust debugging exercise about type errors: integer overflow, truncating casts with as, and types that do not convert the way you expect.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

What went wrong: total and scores.len() as i32 are both integers, so total / len is integer division. 5 / 2 is 2, and the decimal part is thrown away before the result is turned into an f64. Converting afterwards cannot bring back the .5.

The fix: Convert both numbers to f64 first, then divide: total as f64 / scores.len() as f64.

Remember: in Rust, dividing two integers always gives an integer. Cast to f64 before the division, not after it.

The pattern behind it: type errors.

More type errors to practise

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/bd975423-876f-422d-919b-17d4f7282a37" title="Debugging challenge: Average of 2 and 3 comes out as 2.0" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/bd975423-876f-422d-919b-17d4f7282a37">TryBugHunt</a></p>