Python复数类实现:加减运算
class Complex:
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def add(self, other):
real_sum = self.real + other.real
imaginary_sum = self.imaginary + other.imaginary
return Complex(real_sum, imaginary_sum)
def subtract(self, other):
real_diff = self.real - other.real
imaginary_diff = self.imaginary - other.imaginary
return Complex(real_diff, imaginary_diff)
使用示例:
# 创建两个复数对象
c1 = Complex(2, 3)
c2 = Complex(4, 5)
# 计算两个复数的和
sum_result = c1.add(c2)
print(f'Sum: {sum_result.real} + {sum_result.imaginary}i')
# 计算两个复数的差
diff_result = c1.subtract(c2)
print(f'Difference: {diff_result.real} + {diff_result.imaginary}i')
输出结果为:
Sum: 6 + 8i
Difference: -2 - 2i
原文地址: https://www.cveoy.top/t/topic/o8NS 著作权归作者所有。请勿转载和采集!