integer division with float result

renoX renosky at free.fr
Mon Nov 19 21:31:02 PST 2007


Stas Sergeev a écrit :
> Hi.
> 
> This is basically an out of curiosity.
> I wonder how does D handle the integer division.
> In C, as we all know, the following:
> int a = 3;
> int b = 5;
> float c = a / b;
> will give the result that will beat the ghost
> out of any mathematician (unless you cast
> one of the operands to float, of course).

Yep, this is a trap which catch probably all C beginners.

> I haven't used D yet, but I know that most
> (or all?) of the C-unrelated languages do
> that in a proper way, and even the Python
> developers are going to fix that in the future.
 >
> So the question is: how does D handle that?
> Was it infected by the Cish way of handling
> an integer division (if so - why?), or managed
> to get rid of that legacy thingy?

In a statically typed language, the issue is which float type do you use 
for (int / int)?
For accuracy, it ought to be one with biggest precision, but it's also 
the slowest, and can be non-portable (x86 has 80-bit float, other CPU do 
not)

So I came to the conclusion so that maybe removing the / for int/int is 
the only thing to do as it's too ambiguous..
Instead using operators like idiv, fdiv, f64div may be a solution.

renoX






More information about the Digitalmars-d mailing list