c++实现复数的加减乘除
时间: 2023-08-23 21:12:48 浏览: 266
C++实现复数的加减乘除运算
C++ 中可以使用结构体来实现复数的加减乘除。下面是一个简单的实现代码:
```c++
#include <iostream>
using namespace std;
struct Complex {
double real; // 实部
double imag; // 虚部
};
// 复数加法
Complex add(Complex a, Complex b) {
Complex res;
res.real = a.real + b.real;
res.imag = a.imag + b.imag;
return res;
}
// 复数减法
Complex subtract(Complex a, Complex b) {
Complex res;
res.real = a.real - b.real;
res.imag = a.imag - b.imag;
return res;
}
// 复数乘法
Complex multiply(Complex a, Complex b) {
Complex res;
res.real = a.real * b.real - a.imag * b.imag;
res.imag = a.real * b.imag + a.imag * b.real;
return res;
}
// 复数除法
Complex divide(Complex a, Complex b) {
Complex res;
double denominator = b.real * b.real + b.imag * b.imag;
res.real = (a.real * b.real + a.imag * b.imag) / denominator;
res.imag = (a.imag * b.real - a.real * b.imag) / denominator;
return res;
}
int main() {
Complex a = {1, 2};
Complex b = {3, 4};
Complex res_add = add(a, b);
Complex res_subtract = subtract(a, b);
Complex res_multiply = multiply(a, b);
Complex res_divide = divide(a, b);
cout << "a + b = " << res_add.real << " + " << res_add.imag << "i" << endl;
cout << "a - b = " << res_subtract.real << " + " << res_subtract.imag << "i" << endl;
cout << "a * b = " << res_multiply.real << " + " << res_multiply.imag << "i" << endl;
cout << "a / b = " << res_divide.real << " + " << res_divide.imag << "i" << endl;
return 0;
}
```
以上代码中,使用结构体 `Complex` 来表示复数,包括实部 `real` 和虚部 `imag` 两个属性。然后分别实现了复数加法、减法、乘法、除法四个函数。最后在 `main()` 函数中调用这些函数进行测试,并输出结果。
阅读全文