0

I am writing a very simple Fahrenheit to Celsius conversion program that takes a named constant and converts it to Celsius via a simple calculation of (constant - 32) * (5/9)

for whatever reason whenever I run this program it returns 0.0 for Celcius. The math checks out in real life, and the answer is 100, but for whatever reason I keep getting 0.0 from the program. Here's the code:

final double BOILING_IN_F = 212; // Boiling temperature
double fToC;                     // Temperature Celsius
fToC = (BOILING_IN_F - 32) * (5/9);
output = BOILING_IN_F + " in Fahrenheit is " + fToC + " in Celsius.";
System.out.println(output);

I know that when dividing integers, any fractional number will be returned as a whole, which is why I changed my variables to double. Even still, it returns 0. I also tried using float as my data type and switching around the calculation while adding (irrelevant) parentheses.

Jonathan Lam
  • 15,294
  • 14
  • 60
  • 85

3 Answers3

6

5/9 evaluates to 0 since 0.5555555556 rounded towards 0 is 0, which happens because you're using integer division. Change one of the integers to a floating number:

5 / 9.0

If both numbers are integers, it uses integer division which truncates the result. One of the operands must be a non-integer to use non-integer division.

Carcigenicate
  • 35,934
  • 8
  • 48
  • 81
1

Replace

5/9 with 5.0/9.0. This will make sure you get proper division. 5/9 = 0 while 5.0/9.0 = 0.555...

VHS
  • 8,698
  • 3
  • 14
  • 38
0

(5/9) is integer division, resulting in 0.

Dave Drake
  • 323
  • 2
  • 12