Java温度转换程序计算结果不符:95.35°F转°C得35.19而非35.20
华氏转摄氏温度的精度问题修复
问题根源
你的代码在计算摄氏温度时,额外加入了除以100再乘以100的冗余操作——虽然逻辑上数值不变,但浮点数的精度特性可能导致微小误差;再加上DecimalFormat默认的银行家舍入法(ROUND_HALF_EVEN),最终导致输出结果和预期有差异。另外,95.35°F转换为摄氏温度的精确值约为35.1944°C,常规四舍五入到两位小数应为35.19,若你期望得到35.20°C,需调整舍入规则。
修正后的代码
方案1:常规计算(输出35.19°C,符合精确转换结果)
System.out.println("Enter Body Temperature (In F):\n"); double tempF = scan.nextDouble(); DecimalFormat decimalFormat = new DecimalFormat("0.00"); // 直接格式化输入的华氏温度,移除冗余的除法乘法操作 String tempFahrenheit = decimalFormat.format(tempF) + "F"; // 直接完成完整的摄氏温度转换计算 double tempC = (tempF - 32) * 5 / 9.0; String tempCelsius = decimalFormat.format(tempC) + "C"; scan.nextLine(); System.out.printf("Vitals: %s|%s|" , tempFahrenheit , tempCelsius );
方案2:调整舍入规则(输出35.20°C)
如果你确实需要将35.1944°C向上舍入为35.20°C,可以修改DecimalFormat的舍入模式:
import java.math.RoundingMode; // ... 其余代码 ... System.out.println("Enter Body Temperature (In F):\n"); double tempF = scan.nextDouble(); DecimalFormat decimalFormat = new DecimalFormat("0.00"); // 设置为常规四舍五入模式(小数点后第三位>=5则进1) decimalFormat.setRoundingMode(RoundingMode.HALF_UP); String tempFahrenheit = decimalFormat.format(tempF) + "F"; double tempC = (tempF - 32) * 5 / 9.0; String tempCelsius = decimalFormat.format(tempC) + "C"; scan.nextLine(); System.out.printf("Vitals: %s|%s|" , tempFahrenheit , tempCelsius );
关键说明
- 移除冗余的
/100.0和*100.0操作,避免浮点数精度损耗。 DecimalFormat默认采用银行家舍入法,会根据小数点后第三位数字和前一位奇偶性决定舍入方向;若需要常规四舍五入,需手动设置RoundingMode.HALF_UP。
内容的提问来源于stack exchange,提问作者lildroptop
相关产品推荐
相关产品推荐

