You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java温度转换器计算异常:74°F转换结果不符合预期

温度转换器计算错误问题排查

你的转换公式存在两个关键问题:

  • 运算顺序完全颠倒:正确逻辑是先将华氏温度减去32,再乘以转换系数,你现在是先乘后减,这是结果错误的核心原因
  • 系数精度不足:用0.556近似5/9(实际是0.555555...),虽然不是主要问题,但用5.0/9.0能保证计算精度

正确的华氏转摄氏公式为:
tempC = (tempF - 32.0) * 5.0 / 9.0;

把你代码里的错误公式行:

tempC = ((tempF * 0.556) - 32.00);

替换成上面的正确公式后,输入74华氏度就能得到约23.33摄氏度的正确结果。

修正后的完整代码:

import java.util.Scanner;

public class TempConverter {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("What's the temperature outside?");

        double tempF = input.nextInt();

        if (tempF < 45.00) {
            System.out.println(tempF + " degrees? Oh it's a little chilly out there");
        } else {
            System.out.println("Unless it's raining, sounds like a beautiful day!");
        }

        System.out.println("We use a bit of an outdated measurement system over here stubborn as we are. Let's convert that to a measurement you're more familiar with");

        double tempC;
        // 修正后的转换公式
        tempC = (tempF - 32.0) * 5.0 / 9.0;

        System.out.println(tempF + " degrees fahrenheit here in the States should feel like " + tempC + " Celsius back home. Give or take some humidity depending on where that is exactly :)");
    }
}

内容的提问来源于stack exchange,提问作者dietCokeIsTheDevil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 21:22:17