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

Python温度转换脚本输出异常求助:F转C结果始终为0

温度转换脚本错误分析与解决

我是Python新手,编写了degree.py模块及6个温度转换脚本,用于实现摄氏度(C)、华氏度(F)、开尔文(K)之间的互转。其中fahrenheitToCelsius.py脚本负责将华氏度转换为摄氏度,但输出结果始终错误,排查后怀疑是模块中bruh变量始终为0导致,请求帮忙分析问题原因并解决。

原代码

degree.py

#degrees (Celsius, Fahrenheit, Kelvin)

bruh = float(0)
c_1 = float((5/9) * (float(bruh) - 32)) #F to C
c_2 = float((float(bruh) - 273.15) * 1) #K to C
f_1 = float(((9/5) * float(bruh)) + 32) #C to F
f_2 = float((float(bruh)-273.15) * (9/5) + 32) #K to F
k_1 = float((float(bruh) + 273.15) * 1) #C to K
k_2 = float((float(bruh)-32) * (5/9) + 273.15) #F to K

fahrenheitToCelsius.py

import degree

test = False 
while test == False:
    bruh = input("Enter a positive numerical value: ")
    bruh.isnumeric() 
    if bruh.isnumeric() == True:
        print("If the temperature is", bruh, "degrees in Fahrenheit, then it is", degree.c_1, "degrees in Celsius.")
        print()
        print("Do acknowledge that the calculations done here in Python alone are not going to be precise.")
        test = True
    else:
        print("This was not a numerical value bruh :(")
        test = False

问题原因

  1. 静态计算导致结果固定:degree.py中所有转换公式的计算在模块加载时就已完成,使用的是初始值bruh=0。后续即使外部传入新的温度值,这些预先计算好的变量(如c_1)也不会更新,始终是0代入后的结果。
  2. 输入判断逻辑缺陷:bruh.isnumeric()只能识别正整数,输入小数会直接判定为非数值,且未将输入的字符串转换为数值类型就使用。

解决方案

1. 重构degree.py为函数式实现

将静态计算改为函数,每次调用时传入目标温度值,动态计算转换结果:

# degrees (Celsius, Fahrenheit, Kelvin)

def fahrenheit_to_celsius(f):
    return (5/9) * (float(f) - 32)  # F to C

def kelvin_to_celsius(k):
    return float(k) - 273.15  # K to C

def celsius_to_fahrenheit(c):
    return (9/5) * float(c) + 32  # C to F

def kelvin_to_fahrenheit(k):
    return (float(k) - 273.15) * (9/5) + 32  # K to F

def celsius_to_kelvin(c):
    return float(c) + 273.15  # C to K

def fahrenheit_to_kelvin(f):
    return (float(f) - 32) * (5/9) + 273.15  # F to K

2. 修复fahrenheitToCelsius.py的输入处理逻辑

使用try-except捕获数值转换异常,支持整数和小数输入,并调用函数计算结果:

import degree

test = False 
while not test:
    bruh_input = input("Enter a positive numerical value: ")
    try:
        bruh = float(bruh_input)
        if bruh >= 0:
            c_temp = degree.fahrenheit_to_celsius(bruh)
            print(f"If the temperature is {bruh} degrees in Fahrenheit, then it is {c_temp:.2f} degrees in Celsius.")
            print()
            print("Do acknowledge that the calculations done here in Python alone are not going to be precise.")
            test = True
        else:
            print("Please enter a positive value.")
    except ValueError:
        print("This was not a numerical value bruh :(")

修改说明

  • 函数式实现确保每次转换都使用最新传入的温度值,彻底解决初始值固定的问题。
  • try-except结构能正确处理整数、小数输入,同时过滤非数值内容。
  • 格式化字符串让输出更整洁,保留两位小数提升可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:53:17