我得把摄氏温度换算成华氏温度。然而,当我以摄氏度为单位打印温度时,我得到了错误的答案!请帮帮我!(公式是c= (5/9) * (f -32)。当我输入华氏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) //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);
}
}发布于 2012-12-19 14:32:53
你正在做整数除法,因此5 / 9会给出你的0。
将其更改为浮点除法:
c = ((f-32) * (5.0/9));或者,先做乘法(去掉除法中的括号):
c = (f-32) * 5 / 9;因为,f是双精度的。分子将仅为double。我觉得这种方式更好。
发布于 2012-12-19 14:34:24
您应该尝试使用double而不是int,因为这将导致精度损失。一次只使用一个计算,而不是使用整个公式
示例:使用适当的强制转换Double this = 5/9
F-双32
发布于 2012-12-19 14:35:31
而不是使用这个:
c = (int) ((f-32) * (5.0/9));// Calculates the degrees in Celcius 因为它涉及除法,所以您不应该只使用it来获得正确的除法。
https://stackoverflow.com/questions/13946711
复制相似问题