数据结构写一个算法实现复数的四则运算
时间: 2024-10-06 07:02:02 浏览: 26
用C语言实现复数的四则运算
复数的四则运算通常涉及到两个复数的操作:加法、减法、乘法和除法。我们可以将复数表示为(a, b)的形式,其中a是实部,b是虚部。下面是一个简单的Python算法实现:
```python
class ComplexNumber:
def __init__(self, real=0, imag=0):
self.real = real
self.imag = imag
# 加法
def add(self, other):
return ComplexNumber(self.real + other.real, self.imag + other.imag)
# 减法
def subtract(self, other):
return ComplexNumber(self.real - other.real, self.imag - other.imag)
# 乘法
def multiply(self, other):
real_part = self.real * other.real - self.imag * other.imag
imag_part = self.real * other.imag + self.imag * other.real
return ComplexNumber(real_part, imag_part)
# 除法,假设除数不为零
def divide(self, other):
divisor_mag = other.real**2 + other.imag**2
if divisor_mag != 0:
real_divisor = other.real / divisor_mag
imag_divisor = other.imag / divisor_mag
return ComplexNumber((self.real * real_divisor - self.imag * imag_divisor), (self.imag * real_divisor + self.real * imag_divisor))
else:
raise ValueError("Cannot divide by zero")
# 示例使用
c1 = ComplexNumber(2, 3)
c2 = ComplexNumber(4, 5)
add_result = c1.add(c2)
subtract_result = c1.subtract(c2)
multiply_result = c1.multiply(c2)
try:
divide_result = c1.divide(c2)
except ValueError as e:
print(e)
阅读全文