Course contentsShow
← C
Lesson 320 of 1,2194. Control FlowFree lesson

Floating point precision issues in loop conditions

Floating point precision issues in loop conditions

What you'll learn: Why using floating-point numbers like float or double as loop counters can lead to infinite loops or unexpected behavior.

The Mirage of "Equal"

In C, integers are exact. If you count from 1 to 10, the computer hits 10 exactly. Floating-point numbers, however, are stored as binary approximations. Think of them like trying to write the fraction 1/3 as a decimal: you can write 0.3333, but no matter how many 3s you add, it is never exactly 1/3.

In programming, many simple decimals like 0.1 cannot be represented perfectly in binary. Each time you add 0.1 to a total, a tiny "rounding error" accumulates. Eventually, these tiny errors snowball into a big problem for your loop logic.

The Broken Loop

Imagine you want a loop to run until a value reaches exactly 1.0. You might write something like this:

#include <stdio.h>

int main() {
    double counter = 0.0;

    // Danger: This might never be EXACTLY 1.0
    while (counter != 1.0) {
        printf("Counter is: %f\n", counter);
        counter += 0.1;

        // Safety break to prevent a true infinite loop in this example
        if (counter > 1.1) break; 
    }

    return 0;
}

Because 0.1 is slightly "off" in binary, the counter might jump from 0.9999999999999999 to 1.1000000000000001. It completely skips the value 1.0. Since the condition counter != 1.0 remains true, the loop never stops.

The Solution: Think in Ranges

To avoid this pitfall, you should never use == or != with floating-point numbers in a loop condition. Instead, use "Greater Than" or "Less Than" to create a boundary. Even better, use an integer as your loop counter and calculate the decimal value based on that integer.

For example, instead of counting by 0.1, count from 1 to 10 using an int, then divide the result by 10.0. This ensures your loop runs exactly the number of times you expect.

Key takeaway

Never use == or != with floats in loop conditions; use integers for counting to ensure loop stability.