'Add to polynomials”翻译为'多项式相加”,可以通过重载运算符实现多项式的相加。代码示例如下:
#include
#include
#include
using namespace std;
class Polynomial{
private:
vector coef; // 存储多项式系数
public:
Polynomial(){} // 默认构造函数
Polynomial(vector c){ // 重载构造函数
coef = c;
}
friend Polynomial operator+(Polynomial &a, Polynomial &b){ // 重载运算符+
int sizea = a.coef.size();
int sizeb = b.coef.size();
int size = max(sizea, sizeb); // 需要相加的两个多项式的项数最多的那个
vector c(size, 0); // 存储相加后的系数
for(int i=0; i a{1.2, 2.3, 3.4};
vector b{4.5, 5.6, 6.7, 7.8};
Polynomial poly1(a);
Polynomial poly2(b);
Polynomial poly3 = poly1 + poly2;
poly1.print();
poly2.print();
poly3.print();
return 0;
}
输出结果为:
1.20x^0 + 2.30x^1 + 3.40x^2 +
4.50x^0 + 5.60x^1 + 6.70x^2 + 7.80x^3 +
5.70x^0 + 7.90x^1 + 10.10x^2 + 7.80x^3 +