Mail Archives: djgpp/1997/01/07/07:46:03
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 -