Alex Klimashevsky
Alex Klimashevsky

Reputation: 2495

what is better: cast to double or adding double zero?

Lets we have 4 int variables: a, b, c, d

and need to calculate (a * b) / (c * d)

There are 2 ways to do it:

1) double result = ((double)(a * b)) / (c * d)

2) double result = (a * b) / (c * d + 0d)

what are proc and cons for every of this ways?

Upvotes: 1

Views: 103

Answers (2)

Bathsheba
Bathsheba

Reputation: 234665

If you don't mind my saying so, your ways are very bad indeed.

(a * b) is still computed in integral arithmetic so will suffer from wrap-around. (This merely confounds my belief that excess parentheses are a scaled down version of the devil.) In C and C++ it's far worse, the overflow behaviour is undefined and compilers reserve the right to eat your cat.

Worse than that, c * d is also evaluated in integer arithmetic in both cases! The result of this expression is converted to a double.

I believe that 1.0 * a * b / c / d is the clearest way of writing this as a, b, c, and d are all promoted to double types prior to evaluation. My way specifies your intention from the get-go.

Upvotes: 6

Marko Topolnik
Marko Topolnik

Reputation: 200148

One of the cleanest approaches here is relying on automatic promotion that happens in argument passing. Simply declare a method

double multiplyAndDivide(double a, double b, double c, double d) {
    return (a * b) / (c * d);
}

and call it as

return multiplyAndDivide(a, b, c, d);

Upvotes: 6

Related Questions