運行結果展示
代碼如下
class Complex:
def __init__(self, real, virtual):
self.real = real
self.virtual = virtual
def __add__(self, other):
return Complex(self.real + other.real, self.virtual + other.virtual)
def __sub__(self, other):
return Complex(self.real - other.real, self.virtual - other.virtual)
def __mul__(self, other):
return Complex(self.real * other.real - self.virtual * other.virtual,
self.real * other.virtual + other.real * self.virtual)
def __truediv__(self, other):
a = self.real
b = self.virtual
c = other.real
d = other.virtual
devide = c ** 2 + d ** 2
return Complex((a * c + b * d)/devide, (b * c - a * d)/devide)
def __repr__(self):
return "%s + %si" % (self.real, self.virtual)
if __name__ == '__main__':
while True:
print("===輸入第一個複數===")
a = int(input("實部:"))
b = int(input("虛部:"))
print("===輸入第一個複數===")
c = int(input("實部:"))
d = int(input("虛部:"))
c1 = Complex(a, b)
c2 = Complex(c, d)
print("===希望執行的運算===")
sign = int(input("加法(0);減法(1);乘法(2);除法(3);退出(4)"))
if sign == 0:
print("相加的結果爲:", c1 + c2)
print("="*20)
elif sign == 1:
print("相減的結果爲:", c1 - c2)
print("=" * 20)
elif sign == 2:
print("相乘的結果爲:", c1 * c2)
print("=" * 20)
elif sign == 3:
print("相除的結果爲:", c1 / c2)
print("=" * 20)
else:
break
複數除法的數學推導