C++语句复数运算程序
时间: 2023-07-14 22:14:03 浏览: 46
下面是一个简单的 C++ 代码示例,用于计算两个复数的加法、减法和乘法运算。
```cpp
#include <iostream>
using namespace std;
struct Complex {
double real, imag;
};
Complex add(Complex a, Complex b) {
Complex res;
res.real = a.real + b.real;
res.imag = a.imag + b.imag;
return res;
}
Complex sub(Complex a, Complex b) {
Complex res;
res.real = a.real - b.real;
res.imag = a.imag - b.imag;
return res;
}
Complex mul(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;
}
int main() {
Complex a, b, res;
char op;
cout << "Enter the first complex number: ";
cin >> a.real >> a.imag;
cout << "Enter the second complex number: ";
cin >> b.real >> b.imag;
cout << "Enter the operation (+, -, *): ";
cin >> op;
switch (op) {
case '+':
res = add(a, b);
cout << "The result of addition is: " << res.real << " + " << res.imag << "i" << endl;
break;
case '-':
res = sub(a, b);
cout << "The result of subtraction is: " << res.real << " + " << res.imag << "i" << endl;
break;
case '*':
res = mul(a, b);
cout << "The result of multiplication is: " << res.real << " + " << res.imag << "i" << endl;
break;
default:
cout << "Invalid operation." << endl;
break;
}
return 0;
}
```
在此代码中,我们定义了一个 `Complex` 结构体来表示复数。它包含实部和虚部两个成员变量。然后,我们定义了三个函数来执行复数的加法、减法和乘法运算。每个函数都接受两个 `Complex` 类型的参数,并返回一个 `Complex` 类型的结果。最后,我们在 `main()` 函数中读入两个复数和一个运算符,并根据运算符调用相应的函数来计算结果。