www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/01/06/12:46:27

Date: Mon, 6 Jan 1997 19:38:43 +0200 (IST)
From: Eli Zaretskii <eliz AT is DOT elta DOT co DOT il>
To: "M.M. Span" <ïi4 AT is DOT elta DOT co DOT il>
cc: djgpp AT delorie DOT com
Subject: Re: floats and ints
In-Reply-To: <5ar6pi$8go@info.service.rug.nl>
Message-ID: <Pine.SUN.3.91.970106193352.25817B-100000@is>
MIME-Version: 1.0

On 6 Jan 1997, M.M. Span wrote:

> int main( int argc, char** argv )
> {
> 
> int i=1;
> int npoints=500;
> float omega = 0.0
> 
> omega = i/npoints;
> cout << omega << endl;
> 
> return 0;
> }
> 
> yields:
> 
> 0
> 
> casting (float)i/(float)npoints;
> 
> will yield the correct answer.
> 
> is this a bug or a feature.

It's a feature.  When you divide two ints, you get integer division.  The 
compiler couldn't care less about the type of the variable to which you 
assign the result of the division.

To get float division, it is enough to cast only one of the variables to 
floating point; you don't need to cast both of them.

Btw, I suggest you use double instead of float as a general rule, unless 
you are VERY tight on memory and need LARGE arrays of floating numbers.  
x86 CPUs do all floating point operations in the internal 80-bit format 
anyway, so you don't gain any speed by using floats.  You *do* lose a lot 
of accuracy.

- Raw text -


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