TryBugHunt
rustType errorMedium

Rounding -2.7 degrees gives -2

BugFind the bug and fix the code

What it should do

round_temperature(t) rounds a temperature to the nearest whole degree, with halves rounded away from zero. Example: round_temperature(-2.7) → -3

What happens instead

round_temperature(-2.7) returns -2 instead of -3, and round_temperature(-1.5) returns -1 instead of -2.

fn round_temperature(t: f64) -> i32 {
    (t + 0.5) as i32
}

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

A medium 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: Adding 0.5 and casting is an old rounding trick that only works for positive numbers. as i32 truncates toward zero, not down. -2.7 + 0.5 is -2.2, and truncating -2.2 toward zero gives -2. Positive values like 3.6 still come out right, so the bug hides until it is cold.

The fix: Use the built-in t.round(), which rounds to the nearest whole number with halves away from zero, then cast.

Remember: as from float to integer truncates toward zero. Use round(), floor() or ceil() to say exactly which rounding you want, and test negative values.

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/a8bc4229-e6ca-4e8f-81eb-ea97cbd35e4c" title="Debugging challenge: Rounding -2.7 degrees gives -2" 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/a8bc4229-e6ca-4e8f-81eb-ea97cbd35e4c">TryBugHunt</a></p>