1.多项式的系数存放在数组中
# include <iostream>
# include <cstdlib>
# define max(x,y) ((x)>(y)?(x):(y))
using namespace std;
const int N=100;
struct poly
{
int arr[N];
int mexp;
};
void add(poly &a,poly &b,poly &c)
{
memset(c.arr,0,sizeof(c.arr));
c.mexp=max(a.mexp,b.mexp);
int i=0;
for(;i<=c.mexp;i++)
c.arr[i]=a.arr[i]+b.arr[i];
cout<<"add result:"<<endl;
cout<<c.mexp<<endl;
for(i=0;i<=c.mexp;i++)
cout<<c.arr[i]<<" ";
cout<<endl;
}
void mul(poly &a,poly &b,poly &ans)
{
memset(ans.arr,0,sizeof(ans.arr));
ans.mexp=a.mexp+b.mexp;
int i,j;
for(i=0;i<=a.mexp;i++)
for(j=0;j<=b.mexp;j++)
ans.arr[i+j]+=a.arr[i]*b.arr[j];
cout<<"multiply result:"<<endl;
cout<<ans.mexp<<endl;
for(i=0;i<=ans.mexp;i++)
cout<<ans.arr[i]<<" ";
cout<<endl;
}
int main()
{
poly a,b,c;
memset(a.arr,0,sizeof(a.arr));
memset(b.arr,0,sizeof(b.arr));
cout<<"多项式最高幂次"<<endl;
cin>>a.mexp;
int i=0;
cout<<"多项式的各项系数(幂次数递增)"<<endl;
for(;i<=a.mexp;i++)
scanf("%d",&a.arr[i]);
cout<<"多项式最高幂次"<<endl;
cin>>b.mexp;
cout<<"多项式的各项系数(幂次数递增)"<<endl;
for(i=0;i<=b.mexp;i++)
scanf("%d",&b.arr[i]);
add(a,b,c);
mul(a,b,c);
system("pause");
return 0;
}
2.多项式的系数存放在链表结点中
# include <iostream>
# include <cstdlib>
using namespace std;
struct node
{
int key;
int exp;
node *next;
};
node *create()
{
node *head=new node;
head->next=NULL;
node *s=head;
int x,y;
cout<<"请输入系数和次数(次数递增),以0 0结束"<<endl;
while(cin>>x>>y&&(x!=0||y!=0))
{
node *tmp=new node;
tmp->key=x;
tmp->exp=y;
tmp->next=NULL;
s->next=tmp;
s=tmp;
}
return head;
}
node *add(node *h1,node *h2)
{
node *p=h1->next;
node *q=h2->next;
node *s=h1;
node *cur=h1;
while(p&&q)
{
if(p->exp==q->exp)
{
p->key=p->key+q->key;
s->next=p;
s=p;
p=p->next;
q=q->next;
}
else if(p->exp<q->exp)
{
s->next=p;
s=p;
p=p->next;
}
else
{
s->next=q;
s=q;
q=q->next;
}
if(s->key!=0)
{
cur->next=s;
cur=s;
}
}
if(p==NULL)
p=q;
while(p)
{
cur->next=p;
p=p->next;
}
return h1;
}
void display(node *h)
{
node *p=h->next;
while(p)
{
cout<<p->key<<"*x^"<<p->exp<<" ";
p=p->next;
}
cout<<endl;
}
int main()
{
node *h1=create();
node *h2=create();
node *h=add(h1,h2);
cout<<"相加结果:"<<endl;
display(h);
system("pause");
return 0;
}