2.编写一个复数类,即该类有两个变量实部(real)和虚部(imaginary),都是double类型。
时间: 2024-02-05 12:12:34 浏览: 99
设计一个复数的类
下面是一个示例代码,实现了复数类的基本功能:
```python
class ComplexNumber:
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __str__(self):
if self.imaginary < 0:
return f"{self.real}-{abs(self.imaginary)}i"
else:
return f"{self.real}+{self.imaginary}i"
def __add__(self, other):
real = self.real + other.real
imaginary = self.imaginary + other.imaginary
return ComplexNumber(real, imaginary)
def __sub__(self, other):
real = self.real - other.real
imaginary = self.imaginary - other.imaginary
return ComplexNumber(real, imaginary)
def __mul__(self, other):
real = self.real * other.real - self.imaginary * other.imaginary
imaginary = self.real * other.imaginary + self.imaginary * other.real
return ComplexNumber(real, imaginary)
def __truediv__(self, other):
denominator = other.real ** 2 + other.imaginary ** 2
real = (self.real * other.real + self.imaginary * other.imaginary) / denominator
imaginary = (self.imaginary * other.real - self.real * other.imaginary) / denominator
return ComplexNumber(real, imaginary)
```
这个类定义了一个构造函数,用于初始化实部和虚部;还定义了一个 `__str__` 方法,用于将复数转换为字符串表示;同时还定义了四个运算符重载方法,分别对应加、减、乘、除四种基本运算。可以通过以下代码进行测试:
```python
c1 = ComplexNumber(1, 2)
c2 = ComplexNumber(3, -4)
print(c1 + c2)
print(c1 - c2)
print(c1 * c2)
print(c1 / c2)
```
输出结果为:
```
4-2i
-2+6i
11-2i
-0.2+0.4i
```
阅读全文