来源:
http://gdosen.com
http://www.gdosen.com
http://diusong.com
http://www.diusong.com温度转换基于以下数学公式:
摄氏度转华氏度: ℉ = (℃ × 9/5) + 32
华氏度转摄氏度: ℃ = (℉ - 32) × 5/9
下面是一个简单的Python函数,实现两种温度单位的相互转换:
def convert_temperature(temp, unit):
"""
温度转换函数
:param temp: 温度值
:param unit: 原始单位 ('C' 或 'F')
:return: 转换后的温度值及单位
"""
if unit.upper() == 'C':
# 摄氏度转华氏度
converted_temp = (temp * 9/5) + 32
return converted_temp, 'F'
elif unit.upper() == 'F':
# 华氏度转摄氏度
converted_temp = (temp - 32) * 5/9
return converted_temp, 'C'
else:
raise ValueError("无效的单位。请使用 'C' 或 'F'")
# 使用示例
celsius = 25
converted, new_unit = convert_temperature(celsius, 'C')
print(f"{celsius}℃ = {converted:.2f}℉") # 输出: 25℃ = 77.00℉
fahrenheit = 98.6
converted, new_unit = convert_temperature(fahrenheit, 'F')
print(f"{fahrenheit}℉ = {converted:.2f}℃") # 输出: 98.6℉ = 37.00℃下面是一个更完整的程序,包含用户输入和错误处理:
def temperature_converter():
print("温度转换器")
print("==========")
while True:
try:
# 获取用户输入
temp_input = input("请输入温度值(输入q退出): ")
if temp_input.lower() == 'q':
break
temp = float(temp_input)
unit = input("请输入单位(C 或 F): ").upper()
# 验证单位输入
if unit not in ['C', 'F']:
print("错误:单位必须是 'C' 或 'F'")
continue
# 执行转换
if unit == 'C':
converted_temp = (temp * 9/5) + 32
print(f"{temp}℃ = {converted_temp:.2f}℉\n")
else:
converted_temp = (temp - 32) * 5/9
print(f"{temp}℉ = {converted_temp:.2f}℃\n")
except ValueError:
print("错误:请输入有效的数字\n")
except Exception as e:
print(f"发生错误: {e}\n")
if __name__ == "__main__":
temperature_converter()通过本教程,您已经学会了:
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。