www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/02/06/02:06:39

Date: Thu, 6 Feb 1997 08:44:11 +0200 (IST)
From: Eli Zaretskii <eliz AT is DOT elta DOT co DOT il>
To: "Vyacheslav O. Myskin" <myskin AT inp DOT nsk DOT su>
cc: djgpp AT delorie DOT com
Subject: Re: double-->int: What's wrong here?
In-Reply-To: <32f887b7.44544@news-win.inp.nsk.su>
Message-ID: <Pine.SUN.3.91.970206083831.4379F-100000@is>
MIME-Version: 1.0

On Wed, 5 Feb 1997, Vyacheslav O. Myskin wrote:

> The output is:
> n1=214  n2=215  d2=215.000000
> 
> So why  n1 is not equal to n2? It's not fun because I used n1 as an
> argument to malloc() and kept getting SIGSEGVs later :(

Never assume floating-point computations are exact: they aren't.  The
exact reason for what your example printed are immaterial (it's a long and
quite dull story; you might consider adding -S to gcc command line and
looking at the assembly it generates to see what's going on).  The real
lesson is that you should always round the FP numbers explicitly before
using them as counters of anything.  In your case, say n1 = .05/d1 + 0.5
and live happily ever after. 

And btw, you don't need an explicit cast to int, the rules of C make sure 
this is done automagically for you (by truncating the FP value).

- Raw text -


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