Search code examples
cfor-loopequation-solvingnested-for-loop

Why this programme doesn't print the value 2 .. My desire output is 2.. where is the error here


sample code is here, desire output is 2 ::

#include <stdio.h>

int main()
{
    double i, a, b;
    int j;
    for (i = 0; i <= 3; i = i + .20)
    {

        if (i == 2)
        {
            printf("I=%lf\n", i);
        }
    }
}

When I use

#include <stdio.h>

int main()
{
    double i, a, b;
    int j;
    for (i = 0; i <= 3; i = i + .25)
    {

        if (i == 2)
        {
            printf("I=%lf\n", i);
        }
    }
}

it works; but in the first case, it is not working. WHY ??


Solution

  • The short answer is that the use of a floating control variable for a for loop is unwise... comparing a floating value for equality is even less so.

    Due to the storage of floating point numbers as a mantissa and an exponent, your 0.20000000 may well be 0.199999999...9 or 020000000...01 thus the comparison fails.

    Typically, 0.25 and 2.000 will store exactly, as they are powers of 2. Hence a step of 0.25 works as anticipated.

    MISRA C:2012 has Rule 14.1 to protect against using float or doubles as loop counters... and previously had a Rule to protect against testing float/double for equality -perhaps we should reinstate that Rule.