www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - floating point divide

reply "Damian" <damianday hotmail.co.uk> writes:
I come from a pascal background and we could use:
div    integral division operator
/      floating point division operator

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));
Oct 11 2012
next sibling parent "Aziz K." <aziz.koeksal gmail.com> writes:
int n1 = 10, n2 = 2;
float f = (n1+0.0f)/n2;

Casting n1 to float would also work, but I hope the compiler is smart  
enough to optimize away the plus expression.
Oct 11 2012
prev sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
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
Oct 11 2012
parent "Damian" <damianday hotmail.co.uk> writes:
On Thursday, 11 October 2012 at 15:21:01 UTC, bearophile wrote:
 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
Ah i see, thankyou for the explanation.
Oct 11 2012