编写一个类ComplexNumber
时间: 2024-02-27 22:56:54 浏览: 35
好的,以下是一个简单的ComplexNumber类的代码示例:
```python
class ComplexNumber:
def __init__(self, real_part, imaginary_part):
self.real_part = real_part
self.imaginary_part = imaginary_part
def add(self, other):
real = self.real_part + other.real_part
imaginary = self.imaginary_part + other.imaginary_part
return ComplexNumber(real, imaginary)
def subtract(self, other):
real = self.real_part - other.real_part
imaginary = self.imaginary_part - other.imaginary_part
return ComplexNumber(real, imaginary)
def multiply(self, other):
real = self.real_part * other.real_part - self.imaginary_part * other.imaginary_part
imaginary = self.real_part * other.imaginary_part + self.imaginary_part * other.real_part
return ComplexNumber(real, imaginary)
def divide(self, other):
denominator = other.real_part**2 + other.imaginary_part**2
real = (self.real_part * other.real_part + self.imaginary_part * other.imaginary_part) / denominator
imaginary = (self.imaginary_part * other.real_part - self.real_part * other.imaginary_part) / denominator
return ComplexNumber(real, imaginary)
def __str__(self):
if self.imaginary_part >= 0:
return f"{self.real_part} + {self.imaginary_part}i"
else:
return f"{self.real_part} - {-self.imaginary_part}i"
```
这个ComplexNumber类可以用来表示复数,并支持加、减、乘、除四种运算。其中,add()、subtract()、multiply()、divide() 方法分别用于实现复数的加、减、乘、除运算。__str__() 方法用于将复数格式化为字符串输出。当然,这个类还可以根据需要进行扩展,例如添加取模、共轭等方法。