定义一个复数类comp
时间: 2023-07-25 09:47:51 浏览: 47
好的,以下是一个基本的复数类 `comp` 的定义,包含了复数的加减乘除等基本操作。
```python
class comp:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __add__(self, other):
return comp(self.real + other.real, self.imag + other.imag)
def __sub__(self, other):
return comp(self.real - other.real, self.imag - other.imag)
def __mul__(self, other):
return comp(self.real * other.real - self.imag * other.imag, self.real * other.imag + self.imag * other.real)
def __truediv__(self, other):
denominator = other.real**2 + other.imag**2
return comp((self.real * other.real + self.imag * other.imag)/denominator, (self.imag * other.real - self.real * other.imag)/denominator)
def __str__(self):
return f"{self.real} + {self.imag}i"
```
可以通过以下方式使用该类:
```python
a = comp(1, 2)
b = comp(3, -4)
c = a + b
d = a - b
e = a * b
f = a / b
print(c) # 输出 4 - 2i
print(d) # 输出 -2 + 6i
print(e) # 输出 11 - 2i
print(f) # 输出 -0.2 + 0.4i
```
希望这个类能够满足您的需求。