Java 温度转换
我必须把摄氏度转换成华氏度。然而,当我以摄氏度打印温度时,我得到了错误的答案!请帮忙!(公式是c=(5/9)*(f-32)。当我为farenheit度输入1时,我得到c=-0.0。我不知道怎么了:s 这是密码Java 温度转换,java,temperature,Java,Temperature,我必须把摄氏度转换成华氏度。然而,当我以摄氏度打印温度时,我得到了错误的答案!请帮忙!(公式是c=(5/9)*(f-32)。当我为farenheit度输入1时,我得到c=-0.0。我不知道怎么了:s 这是密码 import java.io.*; // import/output class public class FtoC { // Calculates the temperature in Celcius public static void main (String[]args)
import java.io.*; // import/output class
public class FtoC { // Calculates the temperature in Celcius
public static void main (String[]args) //The main class
{
InputStreamReader isr = new InputStreamReader(System.in); // Gets user input
BufferedReader br = new BufferedReader(isr); // manipulates user input
String input = ""; // Holds the user input
double f = 0; // Holds the degrees in Fahrenheit
double c = 0; // Holds the degrees in Celcius
System.out.println("This program will convert the temperature from degrees Celcius to Fahrenheit.");
System.out.println("Please enter the temperature in Fahrenheit: ");
try {
input = br.readLine(); // Gets the users input
f = Double.parseDouble(input); // Converts input to a number
}
catch (IOException ex)
{
ex.printStackTrace();
}
c = ((f-32) * (5/9));// Calculates the degrees in Celcius
System.out.println(c);
}
}
您正在进行整数除法,因此
5/9
将给出0
将其更改为浮点除法:-
c = (f-32) * 5 / 9;
或者,先进行乘法运算(去掉除法中的括号):-
因为,
f
是双精度的。分子只会是double
。我认为这样更好。你在做整数除法,因此5/9
会给出你的0
将其更改为浮点除法:-
c = (f-32) * 5 / 9;
或者,先进行乘法运算(去掉除法中的括号):-
因为,
f
是双精度的。分子只有double
。我认为这种方法更好。你应该尝试使用double而不是int,因为这会导致精度下降。与其使用整个公式,不如一次使用一个计算
示例:使用适当的铸件
双倍于此=5/9
F-Double 32您应该尝试使用Double而不是int,因为这会导致精度损失。不要使用整个公式,而是一次使用一个计算 示例:使用适当的铸件 双倍于此=5/9 F-Double 32使用此选项,而不是:
c = (int) ((f-32) * (5.0/9));// Calculates the degrees in Celcius
由于它涉及除法,您不应仅使用INT来获得正确的除法,请使用以下方法:
c = (int) ((f-32) * (5.0/9));// Calculates the degrees in Celcius
因为它涉及除法,所以不应仅使用INT来获得正确的除法
System.out.println((5F / 9F) * (f - 32F));
用这个
System.out.println((5F / 9F) * (f - 32F));
除非另有明确规定,否则Java将所有数字视为整数。由于整数不能存储数字的小数部分,因此在执行整数除法时,将丢弃余数。因此:
5/9==0
Rohit的解决方案
c=(f-32)*5/9;
可能是最干净的(尽管缺少显式类型可能会引起一些混乱)
Rohit的解决方案c=(f-32)*5/9;
可能是最干净的(尽管缺少显式类型可能会引起一些混乱)。非常感谢大家:)我太困惑了哈哈:谢谢大家:)我太困惑了哈哈:p