1、编写一函数,将摄氏温度与华氏温度互转。(公式: C*1.8+32=F)python
时间: 2023-11-22 16:55:20 浏览: 46
以下是实现该函数的 Python 代码:
```python
def convert_temperature(temp, unit):
"""
Convert temperature between Celsius and Fahrenheit.
:param temp: the temperature value to be converted
:param unit: the unit of the temperature value, either 'C' for Celsius or 'F' for Fahrenheit
:return: the converted temperature value
"""
if unit == 'C':
return temp * 1.8 + 32
elif unit == 'F':
return (temp - 32) / 1.8
else:
raise ValueError("Invalid temperature unit. Please use 'C' for Celsius or 'F' for Fahrenheit.")
```
函数接受两个参数,第一个参数 `temp` 是需要转换的温度值,第二个参数 `unit` 是该温度值的单位,只能是 `'C'` 或 `'F'`。如果 `unit` 是 `'C'`,则将摄氏温度转换为华氏温度;如果 `unit` 是 `'F'`,则将华氏温度转换为摄氏温度。如果 `unit` 不是 `'C'` 或 `'F'`,则会抛出一个异常。
以下是使用该函数进行温度转换的示例:
```python
# 将摄氏温度 25 度转换为华氏温度
fahrenheit = convert_temperature(25, 'C')
print(fahrenheit) # 输出结果为 77.0
# 将华氏温度 68 度转换为摄氏温度
celsius = convert_temperature(68, 'F')
print(celsius) # 输出结果为 20.0
```