编写复数类,并在主类中完成复数的四则运算并输出结果!
时间: 2023-05-14 13:04:52 浏览: 81
实现复数的四则运算
好的,以下是复数类的代码:
class Complex:
def __init__(self, real, imag):
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 = 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):
return f"{self.real} + {self.imag}i"
现在我们可以在主类中使用这个复数类进行四则运算:
a = Complex(1, 2)
b = Complex(3, 4)
print(f"{a} + {b} = {a + b}")
print(f"{a} - {b} = {a - b}")
print(f"{a} * {b} = {a * b}")
print(f"{a} / {b} = {a / b}")
输出结果如下:
1 + 2i + 3 + 4i = 4 + 6i
1 + 2i - 3 - 4i = -2 - 2i
1 + 2i * 3 + 4i = -5 + 10i
1 + 2i / 3 + 4i = 0.44 + 0.08i
希望这个答案能够帮到你!
阅读全文