多项式的和(线性表数组保存)
多项式的和,例如多项式f1(x)=12x^19+13x^8+4x^5-x^3+1,f(x)=21x^21+12x^19+10x^8+4X^6-X^2+3
f1(x)可以表示为(12,19) (13,8) (4,5) (-1,3) (1,0)
f2(x)可以表示为(21,21) (12,19)(10,8)(4,6)(-1,2)(3,0)
f1(x)+f2(x)可表示为(21,21)(24,19)(23,8)(4,6)(4,5)(-1,3)(-1,2)(4,0)
可以用数组来储存系数和指数p3=p1+p2
#include<iostream>
using namespace std;
class ploynode
{
public:
int coef[100]; //储存系数
int expon[100]; //储存指数
};
int main()
{
int i,j,p1num,p2num,count1=0,count2=0,count3=0;
ploynode p1,p2,p3; //p3来保存p1+p2的结果
cin >> p1num;//输入p1的项数
for (i = 0; i < p1num; i++)
cin >> p1.coef[i] >> p1.expon[i];//输入p1的系数和指数
cin >> p2num; //输入p2的项数
for (i = 0; i < p2num; i++)
cin >> p2.coef[i] >> p2.expon[i]; //输入p2的系数和指数
while(count1< p1num&&count2< p2num) //当p1或者p2结束时,结束本次循环
{
if (p1.expon[count1] < p2.expon[count2])
{
p3.expon[count3] = p2.expon[count2];
p3.coef[count3] = p2.coef[count2];
count3++, count2++;
}
else if (p1.expon[count1]>p2.expon[count2])
{
p3.expon[count3] = p1.expon[count1];
p3.coef[count3] = p1.coef[count1];
count3++, count1++;
}
else
{
p3.expon[count3] = p1.expon[count1];
p3.coef[count3] = p1.coef[count1] + p2.coef[count2];
count3++,count2++,count1++;
}
}
if (count1 < p1num) //如果p1还没加完
{
p3.expon[count3] = p1.expon[count1];
p3.coef[count3] = p1.coef[count1];
count3++, count1++;
}
else if (count2 < p2num) //如果p2还没加完
{
p3.expon[count3] = p2.expon[count2];
p3.coef[count3] = p2.coef[count2];
count3++, count2++;
}
for (i = 0; i < count3; i++)
cout << "(" << p3.coef[i] << "," << p3.expon[i] << ") ";
cout << endl;
return 0;
}