C programing problem where <= is interpreted as < when using GCC 11.2.0

Xi Ruoyao xry111@mengyan1223.wang
Thu Oct 14 15:31:41 GMT 2021


On Thu, 2021-10-14 at 15:20 +0000, frijolithedog 1 via Gcc-help wrote:
> I am having a C programing problem where <= is interpreted as < when
> using GCC 11.2.0
> 
> I was debugging a larger program which I broke down into smaller
> sections of code and I noticed
> the following code was not working correctly:
> 
> #include <stdio.h>
> #include <math.h>
> #include <float.h>​
> 
> int main(void)
>  {
>        float n, step;
> 
>        step = 0.1;
> 
>            for (n = 2; n <= 10; n = n + step )
>            printf("%3.4f\n", n );                     /*  This stops
> at 9.9000 and not at 10.0000  */
> 
>  }
> 
> I tried the above code only using the following include statement
> #include <stdio.h>
> but the result was the same.

It's because 0.1 is not something can be represented precisely using
float: it's binary representation is infinite.  The float-type value
closet to 0.1 is 0.100000001490116119384765625, which is slightly larger
than 0.1.

Generally you shouldn't use a floating-point value as a loop iterator
unless you really know what you are doing.
-- 
Xi Ruoyao <xry111@mengyan1223.wang>
School of Aerospace Science and Technology, Xidian University


More information about the Gcc-help mailing list