使用面向对象的程序设计,实现摄氏温度和华氏温度的互转
时间: 2023-11-27 19:50:38 浏览: 23
可以定义一个温度转换器的类,其中包含两个属性:摄氏温度和华氏温度,并且定义两个方法:摄氏温度转换为华氏温度和华氏温度转换为摄氏温度。
以下是一个Python代码示例:
```python
class TemperatureConverter:
def __init__(self, celsius=0, fahrenheit=0):
self.celsius = celsius
self.fahrenheit = fahrenheit
def celsius_to_fahrenheit(self):
self.fahrenheit = (self.celsius * 1.8) + 32
return self.fahrenheit
def fahrenheit_to_celsius(self):
self.celsius = (self.fahrenheit - 32) / 1.8
return self.celsius
# test
converter = TemperatureConverter(0, 32)
print(converter.celsius_to_fahrenheit()) # output: 32.0
print(converter.fahrenheit_to_celsius()) # output: 0.0
```
在这个例子中,我们创建了一个TemperatureConverter类,使用构造函数初始化摄氏温度和华氏温度,然后定义了两个方法,分别将摄氏温度转换为华氏温度和将华氏温度转换为摄氏温度。最后我们进行了测试,将0摄氏度转换为华氏度,输出32.0,然后将32华氏度转换为摄氏度,输出0.0。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)