delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/01/07/07:46:03

From: cziwkga AT ulcc DOT ac DOT uk (Kevin Ashley)
Newsgroups: comp.os.msdos.djgpp
Subject: Re: floats and ints
Date: 7 Jan 1997 09:57:30 GMT
Organization: University of London Computer Centre
Lines: 36
Distribution: world
Message-ID: <5at6ma$130@calypso.ulcc.ac.uk>
References: <5ar6pi$8go AT info DOT service DOT rug DOT nl>
Reply-To: k DOT ashley AT ulcc DOT ac DOT uk
NNTP-Posting-Host: silver-e.ulcc.ac.uk
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

In article <5ar6pi$8go AT info DOT service DOT rug DOT nl>, span AT PROBLEM_WITH_INEWS_GATEWAY_FILE (M.M. Span) writes:
|>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 the way it's meant to work. Since i and npoints are int, the division
is done as integer arithmetic. 1/500 equals 0 if you're working in ints.
The conversion to floating point is done after the division and before the
assignment, since that is when it is perceived to be needed. If you cast
one or another of the variables to float, the computation is done in
floating point. If you think this is odd, consider the converse situation:
if i and npoints were floats and omega an int, you'ld want the division 
done in fp and truncation to int done on the assignment. 

 ------------------------------------------------------------------------------
Kevin Ashley                              K DOT Ashley AT Ulcc DOT ac DOT uk
Systems Development Group Manager      http://www.ulcc.ac.uk/staff/Kevin+Ashley
University of London Computer Centre.      ...ukc!ncdlab!K.Ashley
                      This is not a signature

- Raw text -


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