📄 main.cpp
字号:
#include <iostream>
using namespace std;
struct Poly //定义一个线性表存储多项式
{
int coef;
int exp;
struct Poly *next;
};
typedef struct Poly Poly;
Poly *creatPoly() ;
Poly *Polyadd(Poly *newpoly,int coef,int exp);
Poly *PolyMultiplication (Poly * polya, Poly * polyb);
void Polyprint(Poly *mul);
int main()
{
Poly *polya,*polyb,*mul;
printf("Please input the first Polynomial:\n");
polya=creatPoly();
printf("Please input the second Polynomial:\n");
polyb=creatPoly();
mul=PolyMultiplication(polya,polyb);
printf("The results of the polynomial are:\n");
Polyprint(polya);
printf(" * ");
Polyprint(polyb);
printf(" = ");
Polyprint(mul);
}
Poly *creatPoly() //创建新的多项式
{
Poly *head,*rear,*s;
int c,e;
head=new Poly;
rear=head;
scanf("%d%d",&c,&e);
while (c!=0)
{
s=new Poly;
s->coef=c;
s->exp=e;
rear->next=s;
rear=s;
scanf("%d%d",&c,&e);
}
rear->next=NULL;
return head;
}
Poly *Polyadd(Poly *newpoly,int coef,int exp) //多项式相加 每个线性表与其下一个线性表相加
{
Poly *p=newpoly->next;
Poly *l=newpoly;
while (p!=NULL)
{
if (p->exp<exp)
{
l=p;
p=p->next;
}
else if (p->exp==exp)
{
p->coef+=coef;
{
if (p->coef==0)
{
p=p->next;
delete l->next;
l->next=p;
}
return newpoly;
}
}
else
{
l->next=new Poly;
l->next->next=p;
p=l->next;
p->coef=coef;
p->exp=exp;
return newpoly;
}
}
l->next=new Poly;
p=l->next;
p->coef=coef;
p->exp=exp;
p->next=NULL;
return newpoly;
}
Poly * PolyMultiplication (Poly * polya, Poly * polyb) //多项式相乘
{
int coef, exp;
Poly * newpoly = new Poly ;
newpoly-> next = NULL ;
for ( Poly * f = polya->next ; f!= NULL ;f = f -> next) //多项式的循环相乘
for ( Poly * s = polyb->next ; s != NULL; s = s -> next)
{
coef =(f-> coef )*(s-> coef);
exp = f->exp + s->exp ;
newpoly= Polyadd(newpoly,coef, exp ); //多项式与前一个多项式相加
}
return newpoly;
}
void Polyprint(Poly *mul) //打印多项式结果
{
Poly *p=mul->next;
while (p!=NULL)
{
if (!((p->coef==1||p->coef==-1)&&p->exp!=0))
printf("%d",p->coef);
if (p->exp!=0)
printf("x");
if (p->exp!=1&&p->exp!=0)
printf("(%d)",p->exp);
if (p->next!=NULL&&p->next->coef>0)
printf("+");
if (p->next!=NULL&&p->next->coef<0)
printf("-");a
p=p->next;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -