实验任务:
1. 实现摄氏温度与华氏温度互转(保留两位小数)
2. 扩展功能:输入错误处理(如非数字输入提示重新输入)
3. 扩展:支持开尔文温度的三向转换
实验代码如下:
def temperature_converter():
# 温度类型映射字典
type_map = {
1: ("摄氏", "C"),
2: ("华氏", "F"),
3: ("开尔文", "K")
}
# 输入校验函数
def get_input(prompt, validator):
while True:
try:
value = input(prompt)
return validator(value)
except ValueError as e:
print(f"输入错误:{e},请重新输入")
# 主程序循环
while True:
print("\n" + "="*30)
print("温度转换器(支持摄氏/C、华氏/F、开尔文/K)")
print("="*30)
# 获取温度类型输入
from_type = get_input(
"请输入原始温度类型 (1-摄氏/C, 2-华氏/F, 3-开尔文/K):",
lambda x: type_map[int(x)][0] if x in ['1','2','3'] else (_ for _ in ()).throw(ValueError("请输入1-3"))
)
to_type = get_input(
"请输入目标温度类型 (1-摄氏/C, 2-华氏/F, 3-开尔文/K):",
lambda x: type_map[int(x)][0] if x in ['1','2','3'] else (_ for _ in ()).throw(ValueError("请输入1-3"))
)
# 获取温度值输入
temp = get_input(
"请输入温度值:",
lambda x: float(x)
)
# 温度转换逻辑
try:
# 先统一转成摄氏温度
if from_type == "华氏":
celsius = (temp - 32) * 5/9
elif from_type == "开尔文":
celsius = temp - 273.15
else:
celsius = temp
# 从摄氏转目标类型
if to_type == "华氏":
result = celsius * 9/5 + 32
elif to_type == "开尔文":
result = celsius + 273.15
else:
result = celsius
# 输出结果(自动处理负数情况)
print(f"\n转换结果:{temp:.2f}{type_map[[k for k,v in type_map.items() if v[0]==from_type][0]][1]} → "
f"{result:.2f}{type_map[[k for k,v in type_map.items() if v[0]==to_type][0]][1]}")
except Exception as e:
print(f"转换错误:{str(e)}")
# 继续查询
if input("\n是否继续转换?(y/n):").lower() != 'y':
print("感谢使用温度转换器!")
break
if __name__ == "__main__":
temperature_converter()

实验测试结果如下:
93

被折叠的 条评论
为什么被折叠?



