delorie.com/archives/browse.cgi search
Mail Archives: djgpp/1999/04/13/10:34:38

 Date: Tue, 13 Apr 1999 16:34:13 +0200 From: Hans-Bernhard Broeker Message-Id: <199904131434.QAA03789@acp3bf.physik.rwth-aachen.de> To: djgpp AT delorie DOT com Subject: Re: Qustion on the casting of float's to int's... Newsgroups: comp.os.msdos.djgpp Organization: RWTH Aachen, III. physikalisches Institut B X-Newsreader: TIN [version 1.2 PL2] Reply-To: djgpp AT delorie DOT com

```In article <MPG DOT 117c258b79818b2989680 AT news DOT southwind DOT net> you wrote:

> hi! could some enlightened soul explain to me why this (the
> following) can be?  (thanks!!!)

> here's the code:

>     float i;
>     for (i=0.0; i<29.0; i+=0.2)
>         printf ("(int) %5.1f = %2i \n", i, (int) i);

You've just encountered a pitfall that surprised many beginners,
before they learn how floating point numbers actually work, and what
their limitations are. The basic problem is that '0.2' is not exactly
representable by *any* floating point value, in a PC.  Instead, you'll
get something like 0.1999999.... or 0.20000001...  In the case at
hand, it's the first kind.

Adding up several of these values, you'll see that you won't ever
reach 1.0 exactly. Instead, you get 0.999999999. Because the FPU has
some hidden extra precision, the problem actually does not happen
around a sum of 1.0, but only when it's reached 5.0 or so.

This whole issue is summed up in a nice quote:

In computers, 10 times 0.1 is hardly ever 1.0

> i'm still new to C, but what is the compiler (gcc 2.8.1) doing???
> why does (int)2.0=2 yet (int)8.0=7??? I have always assumed in the
> back of my mind that typecasting floats to ints just rounded down to
> the nearest whole number (ie: truncated the fraction).

Typecasting does that. But *printing* doesn't truncate, it really
rounds. The real floating point value is 7.9999999.... which will be
printed as '8.0', but the truncated value is 7.

--
Hans-Bernhard Broeker (broeker AT physik DOT rwth-aachen DOT de)
Even if all the snow were burnt, ashes would remain.
```

- Raw text -

 webmaster delorie software   privacy Copyright © 2019   by DJ Delorie Updated Jul 2019