2.设计一个温度换算器,实现华氏度、摄氏度、开氏度之问的相互转换。其中,摄氏度 -(华氏度-32)/1.8;华氏度 二摄氏度x1.8+32;开氏度一摄氏度+273.15。
时间: 2023-05-29 10:04:32 浏览: 337
以下是使用Python语言编写的温度换算器代码:
```python
def celsius_to_fahrenheit(celsius):
fahrenheit = celsius * 1.8 + 32
return fahrenheit
def fahrenheit_to_celsius(fahrenheit):
celsius = (fahrenheit - 32) / 1.8
return celsius
def celsius_to_kelvin(celsius):
kelvin = celsius + 273.15
return kelvin
def kelvin_to_celsius(kelvin):
celsius = kelvin - 273.15
return celsius
def fahrenheit_to_kelvin(fahrenheit):
celsius = fahrenheit_to_celsius(fahrenheit)
kelvin = celsius_to_kelvin(celsius)
return kelvin
def kelvin_to_fahrenheit(kelvin):
celsius = kelvin_to_celsius(kelvin)
fahrenheit = celsius_to_fahrenheit(celsius)
return fahrenheit
print("温度换算器\n")
while True:
print("请选择要转换的温度类型:")
print("1. 摄氏度")
print("2. 华氏度")
print("3. 开氏度")
print("4. 退出程序")
choice = int(input())
if choice == 1:
print("请输入摄氏度:")
celsius = float(input())
fahrenheit = celsius_to_fahrenheit(celsius)
kelvin = celsius_to_kelvin(celsius)
print("{:.2f}摄氏度 = {:.2f}华氏度 = {:.2f}开氏度\n".format(celsius, fahrenheit, kelvin))
elif choice == 2:
print("请输入华氏度:")
fahrenheit = float(input())
celsius = fahrenheit_to_celsius(fahrenheit)
kelvin = fahrenheit_to_kelvin(fahrenheit)
print("{:.2f}华氏度 = {:.2f}摄氏度 = {:.2f}开氏度\n".format(fahrenheit, celsius, kelvin))
elif choice == 3:
print("请输入开氏度:")
kelvin = float(input())
celsius = kelvin_to_celsius(kelvin)
fahrenheit = kelvin_to_fahrenheit(kelvin)
print("{:.2f}开氏度 = {:.2f}摄氏度 = {:.2f}华氏度\n".format(kelvin, celsius, fahrenheit))
elif choice == 4:
print("程序已退出。")
break
else:
print("输入有误,请重新选择。\n")
```
代码说明:
- 首先定义了六个函数,分别用于实现摄氏度与华氏度、摄氏度与开氏度、华氏度与开氏度之间的转换。
- 接着进入一个循环,显示菜单并等待用户输入选择。根据用户的选择调用相应的函数进行温度转换,并输出结果。
- 当用户选择“4”退出程序时,跳出循环并显示“程序已退出”。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)