Python实验1 温度转换与输入输出强化

实验任务:

实现摄氏温度与华氏温度互转(保留两位小数)
扩展功能:输入错误处理(如非数字输入提示重新输入)
扩展:支持开尔文温度的三向转换
源代码:

点击查看代码
def c_to_f(c):
    return c * 1.8 + 32

def f_to_c(f):
    return (f - 32) / 1.8

def c_to_k(c):
    return c + 273.15

def k_to_c(k):
    return k - 273.15

def f_to_k(f):
    return c_to_k(f_to_c(f))

def k_to_f(k):
    return c_to_f(k_to_c(k))

def convert(temp_str):
    if temp_str[-1] in ['C', 'c']:
        temp_val = float(temp_str[:-1])
        return f"{c_to_f(temp_val):.2f}F", f"{c_to_k(temp_val):.2f}K"
    elif temp_str[-1] in ['F', 'f']:
        temp_val = float(temp_str[:-1])
        return f"{f_to_c(temp_val):.2f}C", f"{f_to_k(temp_val):.2f}K"
    elif temp_str[-1] in ['K', 'k']:
        temp_val = float(temp_str[:-1])
        return f"{k_to_c(temp_val):.2f}C", f"{k_to_f(temp_val):.2f}F"
    else:
        return None

while True:
    temp_str = input("请输入带有符号的温度值(如20C、68F、293K):")
    if temp_str[:-1].replace('.', '', 1).isdigit() and temp_str[-1] in ['C', 'c', 'F', 'f', 'K', 'k']:
        results = convert(temp_str)
        if results:
            print("转换后的温度是:")
            for result in results:
                print(result)
            break
        else:
            print("输入格式错误,请重新输入")
    else:
        print("输入错误,请输入数字后跟'C', 'F', 或 'K'。")
运行截图:

posted @ 2025-04-18 09:18  是否未晚  阅读(31)  评论(0)    收藏  举报