c++定义两个复数,并对两个复数相加和相减。并显示两个复数的和与差以及相应的复数的实部和虚部,实现五个函数的功能。
时间: 2024-09-20 07:09:13 浏览: 42
在C++中,我们可以使用结构体(struct)来定义复数,包含实部(real)和虚部(imaginary)。以下是实现五个函数(定义、初始化、相加、相减和显示信息)的示例:
```cpp
#include <iostream>
// 定义复数结构体
struct Complex {
double real;
double imaginary;
};
// 初始化复数
Complex create_complex(double real, double imaginary) {
Complex num;
num.real = real;
num.imaginary = imaginary;
return num;
}
// 相加两个复数
Complex add(Complex a, Complex b) {
Complex result;
result.real = a.real + b.real;
result.imaginary = a.imaginary + b.imaginary;
return result;
}
// 相减两个复数
Complex subtract(Complex a, Complex b) {
Complex result;
result.real = a.real - b.imaginary;
return result;
}
// 显示复数及其和差
void display Complex& num) {
std::cout << "复数 (" << num.real << ", " << num.imaginary << "): ";
}
void display_sum(const Complex& a, const Complex& b, const Complex& sum) {
std::cout << "和: (" << sum.real << ", " << sum.imaginary << ")\n";
}
void display_difference(const Complex& a, const Complex& b, const Complex& diff) {
std::cout << "差: (" << diff.real << ", " << diff.imaginary << ")\n";
}
int main() {
// 定义两个复数
Complex num1 = create_complex(1.0, 2.0);
Complex num2 = create_complex(3.0, 4.0);
// 相加
Complex sum = add(num1, num2);
display_sum(num1, num2, sum);
// 相减
Complex difference = subtract(num1, num2);
display_difference(num1, num2, difference);
return 0;
}
```
在这个例子中,`create_complex`用于创建新的复数,`add`和`subtract`分别负责复数的相加和相减操作,`display`用于打印单个复数的信息,而`display_sum`和`display_difference`则展示了两个复数相加和相减后的结果。
阅读全文