3

Im doing a simple piece of java code here, it is a method being called to convert Fahrenheit into Celsius. However when ever i run it, the output is always 0.0.

I cant get it to output the correct calculation. There is probably some silly little thing i have forgotten to do, can someone please help me?

public class ExampleQ {

    public static void main(String[] args) {

        System.out.println(Celsius(50));
    }

    public static double Celsius(double F)
    {
        return (5 / 9) * (F - 32);
    }
}
2
  • 3
    you'd be surprised, but 5/9 == 0 in Java :) 5.0/9 is not though.. Commented Apr 10, 2013 at 6:26
  • And not only in Java :) Commented Apr 10, 2013 at 6:27

6 Answers 6

7

The error is Integer division.

In Java 5 / 9 = 0

Try:

return (5.0 / 9) * (F - 32);
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, i knew it was something small like that, i dont usually get stumped on things like that. Thanks
5

(5/9) produce an integer division with the result "0". As a result it produce 0 for whole expression. Try

return (5.0 / 9) * (F - 32);

Comments

4

Here is the solution. Tested at online compiler Ideone http://ideone.com/zRyG80

Just replace return (5 / 9) * (F - 32); with return (F - 32) * 5 / 9;

Because the reason is in the order of operators execution. In your code division is performed before multiplication which is making 5/9 = 0.

class Main {
    public static void main(String[] args) throws java.lang.Exception {

        System.out.println(Celsius(50));
    }

    public static double Celsius(double F) {
        return (F - 32) * 5 / 9;
    }
}

Output

10.0

1 Comment

+1 for provinding link of an online compiler and debugging tool
3

5 / 9 returns 0, since you're performing integer division.

Use 5.0 / 9.0 instead

Comments

2

(5/9) is interpreted as integer and rounded to 0.0.

To avoid integer you can replace it with (5.0/9).

Comments

2

Or else you can use below code

return (5d / 9d) * (F - 32);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.