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);
    }
}
maba
  • 47,113
  • 10
  • 108
  • 118
drcoding
  • 153
  • 1
  • 3
  • 15

6 Answers6

7

The error is Integer division.

In Java 5 / 9 = 0

Try:

return (5.0 / 9) * (F - 32);
Community
  • 1
  • 1
BobTheBuilder
  • 18,858
  • 6
  • 40
  • 61
  • Awesome, i knew it was something small like that, i dont usually get stumped on things like that. Thanks – drcoding Apr 10 '13 at 06:30
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);
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

Nikhil Agrawal
  • 26,128
  • 21
  • 90
  • 126
3

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

Use 5.0 / 9.0 instead

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
2

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

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

Matt
  • 1,148
  • 10
  • 15
2

Or else you can use below code

return (5d / 9d) * (F - 32);
Ankit HTech
  • 1,863
  • 6
  • 31
  • 42