TryBugHunt
cppType errorMedium

Cart of 29-cent items totals 28 cents

BugFind the bug and fix the code

What it should do

totalCents(prices) adds up prices given in dollars and returns the total in whole cents. Example: totalCents({0.29}) → 29

What happens instead

totalCents({0.29}) returns 28 instead of 29.

#include <cmath>
#include <vector>

int totalCents(std::vector<double> prices) {
    int total = 0;
    for (double p : prices) total += p * 100;
    return total;
}

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 medium 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.29 cannot be stored exactly as a double. 0.29 * 100 is 28.999999999999996, and converting a double to int cuts off the decimals instead of rounding, so the cents come out one short.

The fix: Round before storing the value in an int: std::round(p * 100).

Remember: Converting double to int truncates toward zero. When a decimal value should be a whole number (cents, pixels, counts), round it on purpose. Better still, keep money in whole cents from the start.

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/7689c00a-dc97-4f22-a137-db0cb3f3995f" title="Debugging challenge: Cart of 29-cent items totals 28 cents" 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/7689c00a-dc97-4f22-a137-db0cb3f3995f">TryBugHunt</a></p>