sono2424 sono2424 - 2 years ago 67
Java Question

Why doesn't my temperature conversion calculate correctly?

I am trying to take my Temperature in Fahrenheit and convert it to Celsius. When I call my

method it calculates the Temperature to 0 degrees celsius.

Here is my conversion method

public Temperature toCelsius()
Temperature answer = new Temperature();
case 'C':
answer = new Temperature(this.temp,'C');
return answer;
case 'F':
answer = new Temperature(((this.temp-32)*(5/9)),'C');
return answer;

case 'K':
answer = new Temperature((this.temp-241.15),'C');
return answer;


return answer;

Here is my demo

public class TempDemo {
public static void main(String[] args) {
Temperature temp1 = new Temperature(122, 'F');

Answer Source

5 and 9 are int literals, so dividing them will be done using integer division - i.e., it will take only the whole part of the division. Since 5 is smaller than 9, this will result in 0, and thus so would the entire multiplication.

Instead, you should use double literals:

answer =  new Temperature(((this.temp-32)*(5.0/9.0)), 'C');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download