创建一个复数类Complex,用来执行复数的算术运算,并编写一个程序来测试该类。
时间: 2024-05-12 12:17:05 浏览: 94
好的,关于你的第一个问题,我可以为你解答。
以下是复数类Complex的实现代码:
```python
class Complex:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __add__(self, other):
return Complex(self.real + other.real, self.imag + other.imag)
def __sub__(self, other):
return Complex(self.real - other.real, self.imag - other.imag)
def __mul__(self, other):
return Complex(self.real * other.real - self.imag * other.imag,
self.imag * other.real + self.real * other.imag)
def __truediv__(self, other):
sr, si, o_r, oi = self.real, self.imag, other.real, other.imag
r = float(o_r**2 + oi**2)
return Complex((sr*o_r+si*oi)/r, (si*o_r-sr*oi)/r)
def __str__(self):
return '{}+{}j'.format(self.real, self.imag)
```
我们可以使用该类进行复数的算术运算,例如:
```python
c1 = Complex(2, 3)
c2 = Complex(5, 6)
print(c1 + c2)
print(c1 - c2)
print(c1 * c2)
print(c1 / c2)
```
该程序将输出:
```
7+9j
-3-3j
-8+27j
0.5652173913043478+0.021739130434782608j
```
希望这能为你解决问题!
阅读全文