TryBugHunt
cppType errorHard

Costs of 0.1 and 0.2 do not match a 0.3 budget

BugFind the bug and fix the code

What it should do

matchesBudget(costs, budget) is true when the costs add up to exactly the budget. Example: matchesBudget({0.1, 0.2}, 0.3) → true

What happens instead

matchesBudget({0.1, 0.2}, 0.3) returns false.

#include <cmath>
#include <vector>

bool matchesBudget(std::vector<double> costs, double budget) {
    double sum = 0;
    for (double c : costs) sum += c;
    return sum == budget;
}

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 division, signed and unsigned mix-ups, and implicit conversions that change the value.

What you'll practise

A hard C++ debugging exercise about type errors: integer division, signed and unsigned mix-ups, and implicit conversions that change the value.

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: 0.1, 0.2 and 0.3 cannot be stored exactly in binary. 0.1 + 0.2 is 0.30000000000000004, which is a tiny bit different from the double closest to 0.3, so == says they are not equal.

The fix: Compare with a small tolerance: std::fabs(sum - budget) < 1e-9.

Remember: Never use == on doubles that come from arithmetic. Check that the difference is tiny, or store money as whole cents in an int or long so the sums are exact.

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/36247934-ce0e-496a-a96c-e8743f55e89c" title="Debugging challenge: Costs of 0.1 and 0.2 do not match a 0.3 budget" 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/36247934-ce0e-496a-a96c-e8743f55e89c">TryBugHunt</a></p>