Brainlag
  1. Library
  2. Debugging
  3. C

divide by zeroWhat is "divide by zero"?

Dividing whole numbers by 0 stops a C program while it runs. On a laptop it often says "Floating point exception". Find the value that was 0.

C5 min

What the runtime is telling you

Output
RuntimeError: divide by zero

The program compiled and ran, then reached an int division (/) or remainder (%) where the right-hand side was 0. There is no whole-number answer, so the machine stops the program. On a laptop the same crash is often called Floating point exception, even though no floating point is involved.

With doubles it is different: 5.0 / 0.0 does not stop anything, it gives inf, which then spreads quietly through your maths.

The usual cause is a count that can be 0: the average of an empty list, a K/D ratio with no deaths, a percentage of zero matches.

How to find it

There is no line number, so look for every / and % in the code that ran. For each one, ask: can the right-hand side be 0 here? Print it just before the division to be sure. The fix is a decision, not a trick: what should the answer be when the count is 0? Check for it first and handle it.

Run it: a fresh account

Press Run and read the error from the bottom up.

main.c to run
#include <stdio.h>

int main(void) {
    int total_points = 0;
    int matches = 0;
    printf("matches played: %d\n", matches);
    printf("average: %d\n", total_points / matches);
    return 0;
}

Win rate for a new player

win_rate gives the percentage of games won. It works for Mia but crashes on Jay, who has not played yet. Fix win_rate so a player with no games gets 0. Expected:

Output
Mia 60%
Jay 0%
exercise_1.c to run
#include <stdio.h>

int win_rate(int wins, int games) {
    return wins * 100 / games;
}

int main(void) {
    printf("Mia %d%%\n", win_rate(12, 20));
    printf("Jay %d%%\n", win_rate(0, 0));
    return 0;
}

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.