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

修正摄氏度转华氏度后的风寒指数计算Python代码问题

修复风寒指数计算的摄氏度分支问题

问题分析

当选择摄氏度单位时,代码虽完成了摄氏度到华氏度的转换,但计算风寒指数时仍使用原始摄氏度数值,导致结果错误。风寒指数公式要求输入温度为华氏度,因此必须用转换后的数值参与计算,同时需将最终结果转换回摄氏度输出以匹配用户输入习惯。

原始问题代码示例

temperature = float(input("请输入温度: "))
unit = input("请输入温度单位(C/F): ").upper()
wind_speed = float(input("请输入风速(英里/小时): "))

if unit == 'F':
    wind_chill = 35.74 + 0.6215 * temperature - 35.75 * (wind_speed ** 0.16) + 0.4275 * temperature * (wind_speed ** 0.16)
    print(f"风寒指数: {wind_chill:.1f} °F")
elif unit == 'C':
    # 错误:转换后未使用fahrenheit_temp计算
    fahrenheit_temp = (temperature * 9/5) + 32
    wind_chill = 35.74 + 0.6215 * temperature - 35.75 * (wind_speed ** 0.16) + 0.4275 * temperature * (wind_speed ** 0.16)
    # 额外错误:未将计算结果转换回摄氏度输出
    print(f"风寒指数: {wind_chill:.1f} °C")
else:
    print("无效的温度单位")

修正后的代码

temperature = float(input("请输入温度: "))
unit = input("请输入温度单位(C/F): ").upper()
wind_speed = float(input("请输入风速(英里/小时): "))

if unit == 'F':
    wind_chill = 35.74 + 0.6215 * temperature - 35.75 * (wind_speed ** 0.16) + 0.4275 * temperature * (wind_speed ** 0.16)
    print(f"风寒指数: {wind_chill:.1f} °F")
elif unit == 'C':
    # 1. 将摄氏度转换为华氏度用于公式计算
    fahrenheit_temp = (temperature * 9/5) + 32
    wind_chill_f = 35.74 + 0.6215 * fahrenheit_temp - 35.75 * (wind_speed ** 0.16) + 0.4275 * fahrenheit_temp * (wind_speed ** 0.16)
    # 2. 将计算结果转换回摄氏度输出
    wind_chill_c = (wind_chill_f - 32) * 5/9
    print(f"风寒指数: {wind_chill_c:.1f} °C")
else:
    print("无效的温度单位")

关键修复点

  • 用转换后的华氏温度计算: 在elif unit == 'C'分支中,必须将fahrenheit_temp代入风寒指数公式,而非原始摄氏度值。
  • 结果转回到摄氏度: 公式输出的是华氏度风寒指数,需转换回摄氏度后再输出,符合用户输入的单位预期。

示例运行

输入:
请输入温度: 5
请输入温度单位(C/F): C
请输入风速(英里/小时): 20

输出:
风寒指数: -5.6 °C

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:50:27