1. 使用内置的数学公式进行转换:
def celsius_to_fahrenheit(celsius):
return (celsius * 1.8) + 32
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) / 1.8
2. 使用第三方库,如`numpy`或`pandas`:
import numpy as np
def celsius_to_fahrenheit_np(celsius):
return np.convert_units(celsius, 'degC', 'degF')
def fahrenheit_to_celsius_np(fahrenheit):
return np.convert_units(fahrenheit, 'degF', 'degC')
3. 使用自定义函数进行转换:
def c2f(celsius):
return (celsius * 9/5.0) + 32
def f2c(fahrenheit):
return (fahrenheit - 32) * 5.0/9
4. 通过用户输入进行温度转换:
def get_user_input():
while True:
user_input = input("请输入摄氏温度或华氏温度:")
try:
user_input = float(user_input)
return user_input
except ValueError:
print("输入错误,请输入数字")
def main():
temp = get_user_input()
if temp.endswith(('C', 'c')):
print("华氏温度:", celsius_to_fahrenheit(temp))
elif temp.endswith(('F', 'f')):
print("摄氏温度:", fahrenheit_to_celsius(temp))
else:
print("输入格式错误,请输入带有单位的温度值")
if __name__ == "__main__":
main()
以上代码展示了如何实现摄氏度和华氏度之间的转换。你可以根据需要选择合适的方法进行温度单位转换。