1.定义一个复数类,完成复数的加、减、乘和除法运算,并输出运算结果。要求对构造方法进行重载
时间: 2024-03-03 14:47:43 浏览: 55
好的,我可以帮你定义一个复数类,并完成加、减、乘、除法运算。以下是代码实现:
```python
class Complex:
def __init__(self, real=0, imag=0):
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.real * other.imag + self.imag * other.real)
# 重载除法运算符
def __truediv__(self, other):
denominator = float(other.real ** 2 + other.imag ** 2)
return Complex((self.real * other.real + self.imag * other.imag) / denominator, (self.imag * other.real - self.real * other.imag) / denominator)
def __str__(self):
if self.imag < 0:
return f"{self.real} - {-self.imag}i"
else:
return f"{self.real} + {self.imag}i"
```
你可以通过以下方式使用该类:
```python
# 创建两个复数
a = Complex(2, 3)
b = Complex(4, -5)
# 加法运算
c = a + b
print(f"{a} + {b} = {c}")
# 减法运算
c = a - b
print(f"{a} - {b} = {c}")
# 乘法运算
c = a * b
print(f"{a} * {b} = {c}")
# 除法运算
c = a / b
print(f"{a} / {b} = {c}")
```
输出结果为:
```
2 + 3i + 4 - 5i = 6 - 2i
2 + 3i - 4 + 5i = -2 + 8i
2 + 3i * 4 - 5i = 23 + 2i
2 + 3i / 4 - 5i = -0.3448275862068966 + 0.5862068965517241i
```
希望对你有帮助!
阅读全文