From: Xi Ruoyao <xry111@mengyan1223.wang>
To: frijolithedog 1 <frijolithedog@outlook.com>,
"gcc-help@gcc.gnu.org" <gcc-help@gcc.gnu.org>
Subject: Re: C programing problem where <= is interpreted as < when using GCC 11.2.0
Date: Thu, 14 Oct 2021 23:31:41 +0800 [thread overview]
Message-ID: <b6b142d8aa476447b20337afb43ab6f4285f3988.camel@mengyan1223.wang> (raw)
In-Reply-To: <PSAPR04MB4311D65521A8CD3B0E2820EBB4B89@PSAPR04MB4311.apcprd04.prod.outlook.com>
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
next prev parent reply other threads:[~2021-10-14 15:31 UTC|newest]
Thread overview: 4+ messages / expand[flat|nested] mbox.gz Atom feed top
2021-10-14 15:20 frijolithedog 1
2021-10-14 15:31 ` Xi Ruoyao [this message]
2021-10-14 17:14 ` Jonathan Wakely
2021-10-23 13:43 frijolithedog 1
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=b6b142d8aa476447b20337afb43ab6f4285f3988.camel@mengyan1223.wang \
--to=xry111@mengyan1223.wang \
--cc=frijolithedog@outlook.com \
--cc=gcc-help@gcc.gnu.org \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).