#include <stdio.h>

int main()
{
        float f=0.0f;
        int i;

        for(i=0;i<10;i++)
                f = f + 0.1f;

        if(f == 1.0f)
                printf("f is 1.0 \n");
        else
                printf("f is NOT 1.0\n");

        return 0;
}

Dani AI

Generated

The code posted by triggers the classic floating-point pitfall that suspected: 0.1 cannot be represented exactly in binary IEEE-754 single precision, so adding it repeatedly does not necessarily produce an exact 1.0. A single-precision 0.1f is actually stored as approximately 0.100000001490116119384765625 (hex 0x3DCCCCCD), so ten of those is not exactly 1.0. Behavior can also vary by compiler/architecture because some platforms keep intermediate results in higher precision (x87 80-bit) while others use SSE 32-bit semantics.

Practical fixes:

  • Compare with an epsilon (tolerance) rather than ==:
if (fabsf(f - 1.0f) < 1e-6f) { /* treat as equal */ }

Choose the epsilon to match the magnitude and required precision (for float ~1e-6 to 1e-7; for double ~1e-12 to 1e-15). For robustness use a relative test: fabs(a-b) <= eps * max(1.0f, fabs(a), fabs(b)).

  • Avoid binary floating point where exact decimal fractions are required (money, counts). Use integers or fixed-point arithmetic:
int tenths = 0;
for (i = 0; i < 10; ++i) tenths += 1;   // tenths == 10 -> equals 1.0
  • If you must use floats, print with more digits to inspect errors: printf("%.9f\n", f); or use printf("%.20f\n", (double)f); for diagnosis.

Extra notes: using double reduces but does not eliminate representational error. For summing many small terms consider compensated summation (Kahan) to reduce accumulation error. For financial or legally exact values, use integer cents or a decimal library rather than binary floats. ’s “Problem? What problem?” is the right prompt—the problem is subtle but real, and the remedies above are practical.

Recommended Answers

All 2 Replies

Problem? What problem?

I'm guessing from the code that test if (f == 1.0f) always fails.

This happens because floating point representation in a computer isn't very acurate. Or perhaps too acurate. It depends on your point of view. It is possible that when you increment f ten times with 0.1 intervals, the computer stores the result as 0.999999999999999 (etc). This is almost, but not quite, 1.

Please correct me if I'm wrong :)

commented: Good answer! +9
commented: yes you are absolutely correct. +18
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.