1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| def convert_temperature(temp, from_unit, to_unit): if from_unit == 'C': celsius = temp elif from_unit == 'F': celsius = (temp - 32) * 5 / 9 elif from_unit == 'K': celsius = temp - 273.15 else: raise ValueError("无效的原单位")
if to_unit == 'C': result = celsius elif to_unit == 'F': result = celsius * 9 / 5 + 32 elif to_unit == 'K': result = celsius + 273.15 else: raise ValueError("无效的目标单位")
return result
def main(): print("温度转换程序") print("支持的单位:C(摄氏)、F(华氏)、K(开尔文)")
while True: while True: temp_input = input("请输入温度值:").strip() try: temp = float(temp_input) break except ValueError: print("错误:请输入有效的数字。")
while True: from_unit = input("请输入原单位(C/F/K):").strip().upper() if from_unit in ['C', 'F', 'K']: break else: print("错误:单位必须是C、F或K。")
while True: to_unit = input("请输入目标单位(C/F/K):").strip().upper() if to_unit in ['C', 'F', 'K']: break else: print("错误:单位必须是C、F或K。")
try: converted_temp = convert_temperature(temp, from_unit, to_unit) print(f"转换结果:{converted_temp:.2f} {to_unit}") except ValueError as e: print(f"转换错误:{e}")
another = input("是否继续转换?(输入Y继续,其他退出)").strip().upper() if another != 'Y': print("感谢使用,再见!") break
if __name__ == "__main__": main()
|