使用介绍讲要进行计算的两个式子降幂排列
然后将每一项按系数 指数输入(常数项指数为0)
输入 0 0结束这一项
同理输入第二项
输出第一行为加法
第二行为乘法
代码如下
#include<iostream>
using namespace std;
struct node{
int zhi;
int xi;
node *next;
};
void input(node *p);
node* sum(node *p,node *u);
node* mult(node *p,node *u);
void print(node *p);
int main(){
struct node *a=new node;
input(a);
struct node *b=new node;
input(b);
print(sum(a,b));
//mult(a,b);
print(mult(a,b));
return 0;
}
void input(node *p)
{
p->next=NULL;
node *u=new node;
while(cin>>u->xi>>u->zhi)
{
if(u->xi==0)break;
p->next=u;
u->next=NULL;
p=u;
u=new node;
}
}
node* sum(node *p,node *u)
{
node *a,*b,*l;
node *h=new node;
h->next=NULL;
l=h;
a=p->next;b=u->next;
while(a!=NULL&&b!=NULL)
{
if(a->zhi>b->zhi)
{
node *m=new node;
m->zhi=a->zhi;
m->xi=a->xi;
m->next=NULL;
l->next=m;
l=m;
a=a->next;
}
else if(a->zhi<b->zhi)
{
node *m=new node;
m->zhi=b->zhi;
m->xi=b->xi;
m->next=NULL;
l->next=m;
l=m;
b=b->next;
}
else
{
if(a->xi+b->xi!=0)
{
node *m=new node;
m->xi=a->xi+b->xi;
m->zhi=a->zhi;
m->next=NULL;
l->next=m;
l=m;
b=b->next;
a=a->next;
}
else
{
b=b->next;
a=a->next;
}
}
}
if(a==NULL&&b!=NULL){
while(b!=NULL)
{
node *m=new node;
m->xi=b->xi;
m->zhi=b->zhi;
m->next=NULL;
l->next=m;
l=m;
b=b->next;
}
}
else if(a!=NULL&&b==NULL){
while(a!=NULL)
{
node *m=new node;
m->xi=a->xi;
m->zhi=a->zhi;
m->next=NULL;
l->next=m;
l=m;
a=a->next;
}
}
return h;
}
node* mult(node *p,node *u)
{
int i=0;
node *a=p->next,*b=u->next,*d;
node *t=new node;
t->next=NULL;
d=t;
node *y=new node;
node *r=new node;
r->zhi=0;
r->xi=0;
r->next=NULL;
y->next=r;
while(a!=NULL)
{
b=u->next;
d=t;
while(b!=NULL)
{
node *c=new node;
c->zhi=a->zhi+b->zhi;
c->xi=a->xi*b->xi;
c->next=NULL;
d->next=c;
d=c;
b=b->next;
}
//print(t);
y=sum(y,t);//?aà?3?′í
//print(sum(g,t));
a=a->next;
}
return y;
}
void print(node *p)
{
node *u;
for(u=p->next;u!=NULL;u=u->next)
{
if(u->xi!=1&&u->xi!=-1&&u->xi!=0)cout<<u->xi;
else if(u->xi==-1)cout<<"-";
else if(u->zhi==0&&u->xi!=0)cout<<u->xi;
if(u->zhi>1)cout<<"x^"<<u->zhi;
else if(u->zhi==1)cout<<"x";
if(u->next!=NULL&&u->next->xi>0)cout<<"+";
}
cout<<endl;
}
//版权声明:本文为CSDN博主「jm花」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
//原文链接:https://blog.csdn.net/qq_38556370/article/details/80094770
测试数据
/ | 输入 | 输出 |
---|---|---|
1 | 1 1 1 0 0 0 | 2x+2 |
1 1 1 0 0 0 | x^2+2x+1 | |
2 | 3 5 -7 1 6 0 0 0 | -x^5+2x^2+8 |
-4 5 2 2 7 1 2 0 0 0 | -12^10+6x^7+49x^6-18x^5-14x^3-37x^2+28x+12 |