声明并测试一个复数类,其方法包括toString()及复数的加减乘运算
时间: 2023-06-24 20:08:43 浏览: 157
下面是一个实现了复数类的代码示例,其中包括toString()方法以及复数的加减乘运算:
```python
class Complex:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __str__(self):
if self.imag >= 0:
return f"{self.real}+{self.imag}j"
else:
return f"{self.real}{self.imag}j"
def __add__(self, other):
real = self.real + other.real
imag = self.imag + other.imag
return Complex(real, imag)
def __sub__(self, other):
real = self.real - other.real
imag = self.imag - other.imag
return Complex(real, imag)
def __mul__(self, other):
real = self.real * other.real - self.imag * other.imag
imag = self.real * other.imag + self.imag * other.real
return Complex(real, imag)
```
我们可以进行以下测试:
```python
# 创建两个复数对象
c1 = Complex(1, 2)
c2 = Complex(2, -3)
# 测试toString()方法
print(c1) # 1+2j
print(c2) # 2-3j
# 测试加法运算
c3 = c1 + c2
print(c3) # 3-j
# 测试减法运算
c4 = c1 - c2
print(c4) # -1+5j
# 测试乘法运算
c5 = c1 * c2
print(c5) # 8-1j
```
可以看到,我们成功地实现了复数类,并且测试了其中的方法和运算。
阅读全文