1.构造复数类,包含实部和虚部两个属性,以及求共轭和模长两个方法
2.构造一个计算类,可以计算两个复数的加减乘除
程序怎么写啊
class Complex:
def __init__(self, real_part, imag_part):
self.real_part = real_part
self.imag_part = imag_part
def __add__(self, other): # 加
real = self.real_part + other.real_part
imag = self.imag_part + other.imag_part
return Complex(real, imag)
def __sub__(self, other): # 减
real = self.real_part - other.real_part
imag = self.imag_part - other.imag_part
return Complex(real, imag)
def __mul__(self, other): # 乘
real = (self.real_part * other.real_part) - (self.imag_part * other.imag_part)
imag = (self.real_part * other.imag_part) + (self.imag_part * other.real_part)
return Complex(real, imag)
def __truediv__(self, other): # 除法
conjugate = Complex(other.real_part, -other.imag_part)
numerator = self * conjugate
denominator = (other.real_part ** 2) + (other.imag_part ** 2)
real = numerator.real_part / denominator
imag = numerator.imag_part / denominator
return Complex(real, imag)
def abs(self): # 模长
return (self.real_part * self.real_part + self.imag_part*self.imag_part) ** 0.5
def conj(self): # 求共轭
return Complex(self.real_part, -self.imag_part);
def __str__(self):
strToPrint = "{}+{}i".format(self.real_part, self.imag_part) if self.imag_part>=0 else "{}{}i".format(self.real_part, self.imag_part)
return strToPrint
c = Complex(3, 4) # 创建一个复数c
print(c.conj()) # 打印c的共轭复数
print(c.abs()) # 打印c的模长
c2 = Complex(6, 8)
print(c1 + c2) # 两个复数相加,其它类似
class Complex:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def conjugate(self):
return Complex(self.real, -self.imag)
def modulus(self):
return (self.real ** 2 + self.imag ** 2) ** 0.5
class Calculator:
@staticmethod
def add(c1, c2):
return Complex(c1.real + c2.real, c1.imag + c2.imag)
@staticmethod
def subtract(c1, c2):
return Complex(c1.real - c2.real, c1.imag - c2.imag)
@staticmethod
def multiply(c1, c2):
real = c1.real * c2.real - c1.imag * c2.imag
imag = c1.real * c2.imag + c1.imag * c2.real
return Complex(real, imag)
@staticmethod
def divide(c1, c2):
if c2.real == 0 and c2.imag == 0:
raise ValueError('Cannot divide by zero')
denominator = c2.real ** 2 + c2.imag ** 2
real = (c1.real * c2.real + c1.imag * c2.imag) / denominator
imag = (c1.imag * c2.real - c1.real * c2.imag) / denominator
return Complex(real, imag)
这里定义了一个复数类Complex,它包含了实部和虚部两个属性,以及求共轭和模长两个方法。另外,还定义了一个计算类Calculator,它可以进行两个复数的加减乘除运算,其中加、减、乘、除分别用静态方法实现。