0

I'm making a simple temperature conversion program in Java that converts Fahrenheit to Celsius. My program compiles just fine, but no matter what number I input, it always says that Celsius is 0.0! What could I be doing wrong? Here is my full code:

import javax.swing.JOptionPane;

public class FahrenheitToCelsius {

public static void main(String[] args) {

    double fahrenheit, celsius;

    String input = JOptionPane.showInputDialog("Please enter the temperature in Fahrenheit:");

    fahrenheit = Double.parseDouble(input.trim());

    celsius = (5 / 9) * (fahrenheit - 32);

    JOptionPane.showMessageDialog(null, "The temperature is " + celsius + " degrees celsius.");

    }

}
SoloMael
  • 53
  • 2
  • 9

4 Answers4

5

It's because (5 / 9) = 0.

5 and 9 are both ints, and int division here will result in 0 (5/9 = 0.555..., which can't be an int so it is truncated to 0). Use doubles (5.0 / 9.0) and you won't have this problem.

asaini007
  • 858
  • 5
  • 19
4

In this line:

 celsius = (5 / 9) * (fahrenheit - 32);

5 and 9 are both integer constants, which means that the calculated value will be truncated to 0.

Try instead:

celsius = (5.0 / 9) * (fahrenheit - 32);
stevevls
  • 10,675
  • 1
  • 45
  • 50
3

You are getting 0 cause 5 / 9 is always 0.

What you can do something like this

celsius = ((fahrenheit - 32.0) * 5.0) / 9.0;
Anirban Nag 'tintinmj'
  • 5,572
  • 6
  • 39
  • 59
1

This will work:

celsius = ((fahrenheit - 32) * 5) / 9;

The reason this works has to do with how the operands are grouped. In fahrenheit - 32, fahrenheit is a double and 32 is an int, so the 32 gets promoted to a double, and the result is a double. Then, in:

(fahrenheit - 32) * 5

(fahrenheit - 32) is a double (see above), and 5 is an int, so the 5 gets promoted to a double and the resulting multiplication is a double. Again:

((fahrenheit - 32) * 5) / 9

Now (fahrenheit - 32) * 5 is a double, as we saw above, and 9 is an int, so the 9 gets promoted, and we end up with double-precision floating-point division.

By contrast:

celsius = (fahrenheit - 32) * (5 / 9);

The operands of /, 5 and 9, are both int. So there's no promotion, and the program performs integer division, with an int result. The result will therefore be 0. Now, since fahrenheit - 32 is a double, the 0 will be promoted to a double--but of course it's too late.

The point is that the Java compiler is not a mind-reader; even though the two expressions look the same mathematically, the compiler has a very specific method in which it does things, and programmers must be aware of that.

ajb
  • 31,309
  • 3
  • 58
  • 84