Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math expression that doesn't work with a parenthesis

Tags:

java

I'm tryng to convert a Fahrenheit temperature in correspective Celsius so I wrote:

double f = 90.0;
double c = (90.0-32)*(5/9); // 0.0

But this don't works, better fortune if I don't use the second set of parenthesis:

double c = (90.0-32)*5/9; // 32.2222

Why this (at least for me) strange behavior?

like image 993
BAD_SEED Avatar asked Feb 13 '26 05:02

BAD_SEED


2 Answers

Don't use integers in division since 2/5 = 0 but 2.0/5.0 = 0.4

like image 184
burning_LEGION Avatar answered Feb 14 '26 19:02

burning_LEGION


(90.0-32)*5/9 is evaluated as ((90.0-32)*5)/9, note that the division happens between a double and an int (which is then implicitly cast to double).

In (90.0-32)*(5/9) there is 5/9, which is zero.

like image 34
harold Avatar answered Feb 14 '26 19:02

harold



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!