Mail Archives: djgpp/1997/01/06/12:46:27
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 -