0
public static void main (String[] args) {

   for (double f=0; f<=20;f++) {
      System.out.println(f+":Degrees Fahrenheit converted to Celsius = "+ celsius(f));
   }
}

public static double celsius (double fahrenheit) {
    double cels=(fahrenheit-32)/(5/9);
    return cels;
}

With this program I'm trying to convert Fahrenheit to Celsius, and when I call method Celsius to my main when I run the program the end result for Celsius is always -infinity. What am I doing wrong?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Sagun
  • 11
  • 3
  • The question has already been answered well. But as a note, you can just `return (fahrenheit-32.0)/(5.0/9.0);` You don't actually need the `cels` variable. – nhgrif Oct 30 '13 at 17:52
  • please use for the iterating variable in your for-loop an integer! – Leviathan Oct 30 '13 at 17:56

2 Answers2

4

You're doing int division which always returns an int. For example 5/9 returns 0.

Instead use double division 5.0/9.0

For your code:

public static double celsius (double fahrenheit) {
    return (fahrenheit - 32) / (5.0 / 9.0);
}

We should probably close this question as a duplicate as it's been asked many many times. For example: fahrenheit-to-celsius-conversion-yields-only-0-0-and-0-0

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
2

(5/9) is an integer division, it always returns 0.

It should be: (5.0/9.0)

xorguy
  • 2,594
  • 1
  • 16
  • 14