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);
}
}
(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);
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
5 / 9
returns 0, since you're performing integer division.
Use 5.0 / 9.0
instead
(5/9) is interpreted as integer and rounded to 0.0.
To avoid integer you can replace it with (5.0/9).
或者你可以使用下面的代码
return (5d / 9d) * (F - 32);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.