C++定义一个一元N次多项式的类,能够实现一元多项式的加法, 能够进行输入>>和输出<<运算。使得如下的main函数成立。 int main() { polynomial p1; cin >> p1; polynomial p2; cin >> p2; cout << "p1 = " << p1 << endl; cout << "p2 = " << p2 << endl; cout << "p1+p2 = " << p1 + p2 << endl; return 0; } 输入 两行,分别表示两个多项式的所有系数。每行首先一个正整数n,表示系数有多少项,然后是2n个数,表示多少幂次项的系数。例如, 4 4 3 2 5 1 6 0 -2 3 20 5 4 -7 1 3 输出 两个多项式p1和p2及其加法运算结果。例如, p1 = -2x^0 + 6x^1 + 5x^2 + 3x^4 p2 = 3x^1 + -7x^4 + 5x^20 p1+p2 = -2x^0 + 9x^1 + 5x^2 + -4x^4 + 5x^20
时间: 2024-03-26 22:35:16 浏览: 77
下面是一元N次多项式的类的实现,包含输入、输出和加法运算的重载操作符。
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class polynomial {
private:
vector<int> coef; // 存储系数的向量
public:
polynomial() {} // 默认构造函数
polynomial(int n) : coef(n) {} // 构造函数,指定系数个数
friend istream& operator>>(istream& in, polynomial& p) { // 输入运算符重载
int n;
in >> n;
p.coef.resize(n);
for (int i = 0; i < n; i++) {
in >> p.coef[i];
}
return in;
}
friend ostream& operator<<(ostream& out, const polynomial& p) { // 输出运算符重载
for (int i = 0; i < p.coef.size(); i++) {
if (p.coef[i] != 0) {
out << p.coef[i] << "x^" << i << " + ";
}
}
out << "\b\b "; // 去掉最后的“+ ”
return out;
}
polynomial operator+(const polynomial& p) const { // 加法运算符重载
int n = max(coef.size(), p.coef.size());
polynomial res(n);
for (int i = 0; i < n; i++) {
if (i < coef.size()) {
res.coef[i] += coef[i];
}
if (i < p.coef.size()) {
res.coef[i] += p.coef[i];
}
}
return res;
}
};
int main() {
polynomial p1, p2;
cin >> p1 >> p2;
cout << "p1 = " << p1 << endl;
cout << "p2 = " << p2 << endl;
cout << "p1+p2 = " << p1 + p2 << endl;
return 0;
}
```
输入样例:
```
4 4 3 2 5 1 6 0
-2 3 20 5 4 -7 1 3
```
输出样例:
```
p1 = 4x^0 + 6x^1 + 5x^2 + 0x^3 + 3x^4
p2 = -2x^0 + 3x^1 - 7x^4 + 0x^20
p1+p2 = 2x^0 + 9x^1 + 5x^2 + 0x^3 - 4x^4 + 5x^20
```
阅读全文