使用面向对象程序设计,实现摄氏温度和华氏温度互转
时间: 2023-11-27 21:50:04 浏览: 26
下面是使用 Python 语言实现摄氏温度和华氏温度互转的示例代码:
```python
class TemperatureConverter:
def __init__(self, temperature=0, unit='C'):
self.temperature = temperature
self.unit = unit
def convert_to_celsius(self):
if self.unit == 'F':
self.temperature = (self.temperature - 32) * 5 / 9
self.unit = 'C'
def convert_to_fahrenheit(self):
if self.unit == 'C':
self.temperature = self.temperature * 9 / 5 + 32
self.unit = 'F'
def __str__(self):
return f'{self.temperature:.1f} {self.unit}'
```
说明:
- `TemperatureConverter` 是一个类,用于表示温度转换器。
- `__init__` 方法用于初始化温度和单位,默认值分别为 0 和摄氏度。
- `convert_to_celsius` 方法用于将温度转换为摄氏度。
- `convert_to_fahrenheit` 方法用于将温度转换为华氏度。
- `__str__` 方法用于返回温度和单位的字符串表示。
使用示例:
```python
tc = TemperatureConverter(100, 'C')
print(tc) # 100.0 C
tc.convert_to_fahrenheit()
print(tc) # 212.0 F
tc.convert_to_celsius()
print(tc) # 100.0 C
```