定义一个复数类comp内有实部和虚部两个成员变量还与两个方法 一个求复数的和另一个求复数的积 并在主函数中编写语句验证这两个想法
时间: 2024-03-26 08:40:13 浏览: 18
好的,以下是一个基本的复数类 `comp` 的定义,包含了复数的加和乘两个方法。
```python
class comp:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def sum(self, other):
return comp(self.real + other.real, self.imag + other.imag)
def multiply(self, other):
return comp(self.real * other.real - self.imag * other.imag, self.real * other.imag + self.imag * other.real)
def __str__(self):
return f"{self.real} + {self.imag}i"
```
可以通过以下方式使用该类:
```python
a = comp(1, 2)
b = comp(3, -4)
c = a.sum(b)
d = a.multiply(b)
print(c) # 输出 4 - 2i
print(d) # 输出 11 - 2i
```
其中,`sum` 方法实现了复数的加法,`multiply` 方法实现了复数的乘法。在主函数中,我们首先创建了两个复数对象 `a` 和 `b`,然后分别调用了 `sum` 和 `multiply` 方法来计算它们的和和积,并打印出结果。
希望这个类能够满足您的需求。