答案是摄氏温度转换为华氏温度的公式为华氏温度=摄氏温度×9/5+32,Python中可通过input输入数值并用float转换类型,基础实现包括直接计算输出、封装为函数celsius_to_fahrenheit便于调用,进一步可扩展convert_temperature函数支持双向转换,通过unit参数判断转换方向,C转F使用公式value×9/5+32,F转C使用(value-32)×5/9,同时加入单位验证和异常处理提升程序健壮性。

将摄氏温度转换为华氏温度是常见的编程练习。公式很简单:华氏温度 = 摄氏温度 × 9/5 + 32。下面用 Python 实现这个功能。
基础版本:手动输入摄氏度
用户输入一个摄氏温度,程序输出对应的华氏温度。
celsius = float(input("请输入摄氏温度: "))
fahrenheit = celsius * 9/5 + 32
print(f"对应的华氏温度是: {fahrenheit}")
封装成函数
把转换过程写成函数,便于重复使用。
def celsius_to_fahrenheit(c):
return c * 9/5 + 32
使用示例
temp_c = 25
temp_f = celsius_to_fahrenheit(temp_c)
print(f"{temp_c}°C 等于 {temp_f}°F")
支持双向转换
扩展功能,支持华氏转摄氏,增加灵活性。
立即学习“Python免费学习笔记(深入)”;
def convert_temperature(value, unit):
if unit.lower() == 'c':
return value * 9/5 + 32 # C 到 F
elif unit.lower() == 'f':
return (value - 32) * 5/9 # F 到 C
else:
return "单位错误,请使用 'C' 或 'F'"
示例
print(convert_temperature(100, 'C')) # 输出 212.0
print(convert_temperature(32, 'F')) # 输出 0.0
基本上就这些。不复杂但容易忽略细节,比如输入类型转换和单位验证。实际使用时可加入异常处理增强健壮性。











