#include <iostream> using namespace std; class Polynomial{ private: double *coefficients; //动态数组,用来存储多项式各项系数 int size; //多项式的大小,项数,最高次项的幂为size-1 public: Polynomial(int size=1); //已实现 Polynomial(double* coets, int size);//已实现 friend ostream& operator<<(ostream& os, const Polynomial& p); //已实现 ~Polynomial(); //已实现 Polynomial(const Polynomial &poly); //已实现 Polynomial& operator+=(const Polynomial& p); };int main() { int n1, n2; cin >> n1 >> n2; double a1[n1], a2[n2]; for(int i=0; i<n1; i++) cin >> a1[i]; for(int i=0; i<n2; i++) cin >> a2[i]; Polynomial p1(a1, n1); Polynomial p2(a2, n2); Polynomial pp; pp += p1; cout << pp << endl; p2 += pp; cout << p2 << endl; return 0; } /* 请在这里填写答案,你只需要完成复合赋值(+=)运算符函数即可,其他均已由系统实现
时间: 2023-06-19 15:03:35 浏览: 273
使用include <iostream>时一定要加using namespace std
class Polynomial {
private:
double *coefficients;
int size;
public:
Polynomial(int size = 1) {
this->size = size;
coefficients = new double[size];
for(int i = 0; i < size; i++) {
coefficients[i] = 0;
}
}
Polynomial(double* coets, int size) {
this->size = size;
coefficients = new double[size];
for(int i = 0; i < size; i++) {
coefficients[i] = coets[i];
}
}
friend ostream& operator<<(ostream& os, const Polynomial& p) {
for(int i = p.size - 1; i >= 0; i--) {
if(p.coefficients[i] != 0) {
if(i != p.size - 1 && p.coefficients[i] > 0) {
os << "+";
}
if(p.coefficients[i] != 1 && p.coefficients[i] != -1) {
os << p.coefficients[i];
} else if(p.coefficients[i] == -1) {
os << "-";
}
if(i > 1) {
os << "x^" << i;
} else if(i == 1) {
os << "x";
} else {
os << p.coefficients[i];
}
}
}
return os;
}
~Polynomial() {
delete[] coefficients;
}
Polynomial(const Polynomial &poly) {
size = poly.size;
coefficients = new double[size];
for(int i = 0; i < size; i++) {
coefficients[i] = poly.coefficients[i];
}
}
Polynomial& operator+=(const Polynomial& p) {
int newSize = max(this->size, p.size);
double* newCoefficients = new double[newSize];
for(int i = 0; i < newSize; i++) {
if(i < this->size && i < p.size) {
newCoefficients[i] = this->coefficients[i] + p.coefficients[i];
} else if(i < this->size) {
newCoefficients[i] = this->coefficients[i];
} else {
newCoefficients[i] = p.coefficients[i];
}
}
delete[] coefficients;
coefficients = newCoefficients;
size = newSize;
return *this;
}
};
阅读全文