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

知识点:input()/print()、分支语句、字符串处理(教材2.1-2.2)
实验任务:
1. 实现摄氏温度与华氏温度互转(保留两位小数)
2. 扩展功能:输入错误处理(如非数字输入提示重新输入)
3. 扩展:支持开尔文温度的三向转换

def temperature_converter():
    units = {'C': '摄氏', 'F': '华氏', 'K': '开尔文'}

    while True:
        try:
            # 获取温度值输入
            temp_input = input("请输入温度值(输入q退出):").strip()
            if temp_input.lower() == 'q':
                print("程序已退出")
                break
            temp = float(temp_input)

            # 获取原始单位
            while True:
                from_unit = input("请输入原始单位(C/F/K):").upper().strip()
                if from_unit in units:
                    break
                print("错误:请输入有效的单位(C/F/K)")

            # 获取目标单位
            while True:
                to_unit = input("请输入目标单位(C/F/K):").upper().strip()
                if to_unit in units and to_unit != from_unit:
                    break
                print("错误:请输入不同的有效单位(C/F/K)")

            # 温度转换逻辑
            if from_unit == 'C':
                if to_unit == 'F':
                    result = temp * 9 / 5 + 32
                else:  # K
                    result = temp + 273.15
            elif from_unit == 'F':
                if to_unit == 'C':
                    result = (temp - 32) * 5 / 9
                else:  # K
                    result = (temp - 32) * 5 / 9 + 273.15
            else:  # K
                if to_unit == 'C':
                    result = temp - 273.15
                else:  # F
                    result = (temp - 273.15) * 9 / 5 + 32

            # 输出结果
            print(f"转换结果:{temp:.2f}°{from_unit} = {result:.2f}°{to_unit}\n")

        except ValueError:
            print("错误:请输入有效的数字温度值\n")
        except KeyboardInterrupt:
            print("\n检测到中断,程序已退出")
            break


if __name__ == "__main__":
    temperature_converter()

4.运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值