Trouble with calling method [duplicate]

℡╲_俬逩灬. 提交于 2019-12-02 16:40:08

问题


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?


回答1:


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




回答2:


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

It should be: (5.0/9.0)



来源:https://stackoverflow.com/questions/19690271/trouble-with-calling-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!