c++问题描述: 设有一元多项式am(x)和bn(x). am(x)=a0+a1x1+a2x2+a3x3+….+amxm b
时间: 2023-09-29 17:06:13 浏览: 151
C++代码如下:
```c++
#include <iostream>
#include <vector>
using namespace std;
// 定义一元多项式结构体
struct Polynomial {
vector<double> coeff; // 系数数组
int degree; // 最高次数
};
// 计算两个多项式的和
Polynomial addPolynomial(const Polynomial& a, const Polynomial& b) {
Polynomial result;
int maxDegree = max(a.degree, b.degree);
result.coeff.resize(maxDegree + 1);
for (int i = 0; i <= maxDegree; i++) {
double aCoeff = (i <= a.degree) ? a.coeff[i] : 0;
double bCoeff = (i <= b.degree) ? b.coeff[i] : 0;
result.coeff[i] = aCoeff + bCoeff;
}
result.degree = maxDegree;
return result;
}
int main() {
// 示例:计算 am(x) + bn(x)
Polynomial am, bn;
am.coeff = {1, 2, 3}; // am(x) = 1 + 2x + 3x^2
am.degree = 2;
bn.coeff = {4, 5}; // bn(x) = 4 + 5x
bn.degree = 1;
Polynomial sum = addPolynomial(am, bn);
cout << "am(x) + bn(x) = ";
for (int i = sum.degree; i >= 0; i--) {
cout << sum.coeff[i] << "x^" << i;
if (i > 0) cout << " + ";
}
cout << endl;
return 0;
}
```
输出结果为:am(x) + bn(x) = 1x^2 + 2x^1 + 7x^0
阅读全文