【发布时间】:2014-05-01 18:20:10
【问题描述】:
我在使用 Java 程序时遇到问题,Java E6B 飞行计算机突然停止将华氏温度转换为摄氏温度,它始终输出 0,无论是什么值,摄氏温度到华氏温度的写法相似并且工作正常,两个函数都写入一个日志文件,这是有效的,除了华氏度到摄氏温度对于日志文件中的任何输入都显示为 0。 (我知道我拼错了华氏度)。我考虑过改成 Double 而不是浮点数
这是两个函数的代码。还包括舍入功能。
public static String celstofare(String Celsius){
// function level
float a;
// if user types string, returns error
try
{
a = Float.parseFloat(Celsius);
float math = ((a * (9/5)) + 32);
String out = round(math, 2) +"";
// log file update mechanism
File file = new File("log.txt");
FileWriter writer;
try {
writer = new FileWriter(file, true);
PrintWriter printer = new PrintWriter(writer);
Date date = new Date();
String strDate = date.toString();
printer.println("Converted Celsius to Farenheit on: " + strDate);
printer.println("Celsius: " + a + "Farenheit: " + out);
printer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return out;
}
catch (Exception e)
{
return "error";
}
}
public static String faretocels(String Farenheit){
// function level
float a;
// if user types string, returns error
try
{
a = Float.parseFloat(Farenheit);
float math = ((a - 32) * (5/9));
String out = round(math, 2) +"";
// log file update mechanism
File file = new File("log.txt");
FileWriter writer;
try {
writer = new FileWriter(file, true);
PrintWriter printer = new PrintWriter(writer);
Date date = new Date();
String strDate = date.toString();
printer.println("Converted Farenheit to Celsius on: " + strDate);
printer.println("Farenheit: " + a + "Celsius: " + out);
printer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return out;
}
catch (Exception e)
{
return "error";
}
}
public static BigDecimal round(double d, int decimalPlace) {
BigDecimal bd = new BigDecimal(Double.toString(d));
bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
return bd;
}
这里是调用它的函数和动作监听器,其他一切正常,我已经验证了正确的输入和输出设置。输入和输出框是 JTextFields
else if (e.getSource() == btnCalculateConversion){
mphOut.setText(Conversions.KnotstoMph(knots.getText()));
knotsOut.setText(Conversions.mphtoknots(mph.getText()));
nmout.setText(Conversions.mphtoknots(mph.getText()));
miout.setText(Conversions.KnotstoMph(knots.getText()));
poundsout.setText(Conversions.galtopound(gal.getText()));
galout.setText(Conversions.poundtogal(pounds.getText()));
tempfout.setText(Conversions.celstofare(tempc.getText()));
tempcout.setText(Conversions.faretocels(tempf.getText()));
【问题讨论】:
-
您的
5/9和9/5的算术正在使用 integer 算术执行...试试5f/9和9f/5。 -
5/9是int除数,并且始终等于 0。
标签: java math floating-point type-conversion jtextfield