You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

57 lines
1.4 KiB

# 温度转换器示例程序(Python)
# 支持摄氏度(C)与华氏度(F)之间互转
def celsius_to_fahrenheit(c):
"""将摄氏度转换为华氏度。
参数:
c (float): 摄氏温度
返回:
float: 对应的华氏温度
"""
return c * 9.0 / 5.0 + 32.0
def fahrenheit_to_celsius(f):
"""将华氏度转换为摄氏度。
参数:
f (float): 华氏温度
返回:
float: 对应的摄氏温度
"""
return (f - 32.0) * 5.0 / 9.0
def main():
# 提示用户输入,格式示例:"36.6 C" 或 "97 F"
s = input('请输入要转换的温度与单位(例如 36.6 C 或 97 F):').strip()
if not s:
print('输入为空,程序退出。')
return
parts = s.split()
try:
# 允许用户输入两个部分:数值与单位
value = float(parts[0])
unit = parts[1].upper() if len(parts) > 1 else 'C'
except Exception as e:
print('输入解析失败,请按示例输入数值与单位,例如:36.6 C')
return
if unit.startswith('C'):
# 从摄氏度转换为华氏度
f = celsius_to_fahrenheit(value)
print(f"{value} °C = {f:.2f} °F")
elif unit.startswith('F'):
# 从华氏度转换为摄氏度
c = fahrenheit_to_celsius(value)
print(f"{value} °F = {c:.2f} °C")
else:
print('未知单位,请使用 C 或 F。')
if __name__ == '__main__':
main()