设计一个可进行复数运算的演示程序。要求实现下列6种基本运算: (1)由输入的实部和虚部生成一个复数。 (2)两个复数求和。 (3)两个复数求差 (4)两个复数求积 (5)从已知复数中分离出实部。 (6)从已知复数中分离出虚部
时间: 2024-06-06 15:07:33 浏览: 5
以下是Python实现的示例代码:
class ComplexNumber:
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __add__(self, other):
return ComplexNumber(self.real + other.real, self.imaginary + other.imaginary)
def __sub__(self, other):
return ComplexNumber(self.real - other.real, self.imaginary - other.imaginary)
def __mul__(self, other):
return ComplexNumber(self.real * other.real - self.imaginary * other.imaginary, self.real * other.imaginary + self.imaginary * other.real)
def get_real(self):
return self.real
def get_imaginary(self):
return self.imaginary
def __str__(self):
return "{} + {}i".format(self.real, self.imaginary)
# 测试样例
c1 = ComplexNumber(2, 3)
c2 = ComplexNumber(4, -5)
print("c1 =", c1)
print("c2 =", c2)
print("c1 + c2 =", c1 + c2)
print("c1 - c2 =", c1 - c2)
print("c1 * c2 =", c1 * c2)
print("real part of c1 =", c1.get_real())
print("imaginary part of c1 =", c1.get_imaginary())
相关推荐
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)