floating point divide
bearophile
bearophileHUGS at lycos.com
Thu Oct 11 07:56:51 PDT 2012
Damian:
> I come from a pascal background and we could use:
> div integral division operator
> / floating point division operator
Two operators for the two different operations is a design better
than C, that is bug-prone.
> So my question is, how does D force floating point division on
> integrals?
> At the moment i do this, but i was hoping for an easier way:
>
> int n1 = 10, n2 = 2;
> float f = cast(float)(cast(float)(n1 / n2));
That's not good, it performs an integer division, followed by two
float casts.
Note: float is useful only if you have many of them, or if you
pass/return pairs of them. A single float is not so useful.
A solution:
int n1 = 10, n2 = 2;
const f = n1 / cast(double)n2;
Using type inference is useful, as it doesn't hide an integer
result if your code is wrong.
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list