cast(int) getting an unexpected number

Ali Cehreli acehreli at yahoo.com
Wed Nov 4 12:32:53 PST 2009


Ok, I messed up my previous comment while moving rmcguire's lines around. Trying again... Also, I am not sure about the last bit now. :)

rmcguire Wrote:

> why is this not a compiler bug?
> because:
> import std.stdio;
> 
> void main() {
>         float f=0.01;

Just an information: 0.01 is double, there is type conversion there.

>         writefln("%0.2f->%d",f,cast(int)(f*100f));
> results in:
> 0.01->0

f*100f is represented to be less than 0.

>         writefln("%0.2f->%d",f,cast(int)(.01*100f));
> results in:
> 0.01->1

.01 * 100f is double and apparently represented as something more than 1.

>         writefln("%0.2f->%f",f,(f*100f));
> results in:
> 0.01->1.000000

If it's like in C, floating point values must be passed as double arguments to functions. So there is float-to-double conversion before the function call, effectively representing the argument as double.

Ali



More information about the Digitalmars-d-learn mailing list