使用线性表实现两个一元n次多项式求和。1<=多项式项数,指数<=105,多项式不为空
时间: 2024-01-25 08:06:24 浏览: 93
好的,这里给出一个完整的代码实现。
```
#include <iostream>
using namespace std;
const int MAXSIZE = 100000;
struct Term {
float coef; // 系数
int expn; // 指数
};
struct Polynomial {
char name; // 多项式名称
int length; // 多项式项数
Term terms[MAXSIZE]; // 多项式项数组
};
void inputPolynomial(Polynomial &p) {
cout << "请输入多项式" << p.name << "的项数:";
cin >> p.length;
for (int i = 0; i < p.length; i++) {
cout << "请输入多项式" << p.name << "的第" << i + 1 << "项的系数和指数:";
cin >> p.terms[i].coef >> p.terms[i].expn;
}
}
void addPolynomial(Polynomial a, Polynomial b, Polynomial &c) {
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length) {
if (a.terms[i].expn == b.terms[j].expn) {
float sum = a.terms[i].coef + b.terms[j].coef;
if (sum != 0) {
c.terms[k].coef = sum;
c.terms[k].expn = a.terms[i].expn;
k++;
}
i++;
j++;
} else if (a.terms[i].expn > b.terms[j].expn) {
c.terms[k].coef = a.terms[i].coef;
c.terms[k].expn = a.terms[i].expn;
k++;
i++;
} else {
c.terms[k].coef = b.terms[j].coef;
c.terms[k].expn = b.terms[j].expn;
k++;
j++;
}
}
while (i < a.length) {
c.terms[k].coef = a.terms[i].coef;
c.terms[k].expn = a.terms[i].expn;
k++;
i++;
}
while (j < b.length) {
c.terms[k].coef = b.terms[j].coef;
c.terms[k].expn = b.terms[j].expn;
k++;
j++;
}
c.length = k;
}
void printPolynomial(Polynomial p) {
for (int i = 0; i < p.length; i++) {
cout << p.terms[i].coef << "x^" << p.terms[i].expn;
if (i != p.length - 1) {
cout << " + ";
}
}
cout << endl;
}
int main() {
Polynomial a = {'A', 0, {}};
Polynomial b = {'B', 0, {}};
Polynomial c = {'C', 0, {}};
inputPolynomial(a);
inputPolynomial(b);
addPolynomial(a, b, c);
cout << "多项式A:";
printPolynomial(a);
cout << "多项式B:";
printPolynomial(b);
cout << "多项式C=A+B:";
printPolynomial(c);
return 0;
}
```
在输入多项式时,程序会先要求用户输入多项式的项数,然后逐一输入每一项的系数和指数。在求和时,程序会遍历两个多项式的所有项,将指数相同的项的系数相加,结果存储到新的多项式中。最后输出三个多项式的信息,包括名称和各个项的系数和指数。
阅读全文