#25 · Numbers

Find the bug · #25 · Numbers Easy Java

Progress is always 0%

The course page shows 0% done until the last lesson, then jumps straight to 100%.

On this page

The report

Bug report

The course page shows how much of the course you’ve finished. It says 0% all the way through, until the very last lesson, when it jumps to 100%.

The code

Read it first: what should it do? Then click the line where you think the bug is.

JavaClick the line you think is wrong
class Course {
    // How much of the course is done, as a whole percentage.
    static int percentDone(int done, int total) {
        return done / total * 100;
    }
}

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
System.out.println(Course.percentDone(3, 12));
System.out.println(Course.percentDone(12, 12));

It prints

0
100

It should print

25
100
Show the answer: the bug, the fix, and how you’d find it

The bug (line 4)

Line 4 divides two ints first. 3 / 12 is 0 in integer division (the fraction is thrown away), and 0 × 100 is still 0. Multiply first, done * 100 / total, so the division happens last, on a bigger number.

The fix

1class Course {2    // How much of the course is done, as a whole percentage.3    static int percentDone(int done, int total) {4        return done / total * 100;4        return done * 100 / total;5    }6}

How you’d find it

  1. Reproduce mid-course: 3 of 12 lessons done gives 0, not 25.
  2. Work out the expression one step at a time with ints: 3 / 12 is 0. Everything after that is multiplying zero.
  3. Only the order of operations is wrong: the same numbers, multiplied before dividing, give 25.

The test that catches it

It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.

check(Course.percentDone(3, 12) == 25, "a quarter");
check(Course.percentDone(1, 3) == 33, "rounds down");
check(Course.percentDone(0, 5) == 0, "none done");

Where else this bites

  • Python 3’s / is true division, but // floors; C, C++, Java and Go all drop the fraction for ints.
  • Average ratings worked out as sum / count on ints.
Your progress stays on this device.