1

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 ??

康桓瑋
  • 33,481
  • 5
  • 40
  • 90
Plaban Das
  • 23
  • 6
  • It is because double can not represent .20 precisely but can do so with .25, print your variable at the start of the loop and see for yourself. – Klaus Mar 14 '22 at 12:30
  • If you `printf("%.16f\n", i);` in each loop you'll see the first example gives `1.9999999999999998`. – Weather Vane Mar 14 '22 at 12:38

1 Answers1

2

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.

Andrew
  • 2,046
  • 1
  • 24
  • 37