问题
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