修正一点儿粗心小错误:#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct Polynomial
{
float coef;
int expn; //指数
struct Polynomial *next;
}*Polyn;
void InitPolyn(Polyn *P);
void CreatPolyn(Polyn *P,int m);//创建一个多项式
void ShowPolyn(Polyn P);//打印出多项式
void SortPolyn(Polyn P);//按指数降序排列
void AddPolyn(Polyn Pa,Polyn Pb,Polyn Pc);//Pc = Pa + Pb
void SubPolyn(Polyn Pa,Polyn Pb,Polyn Pc);//Pc = Pa - Pb
void valPolyn(Polyn *P,int x);//求多项式当X为多少的值
void InitPolyn(Polyn *P)
{
*P = (Polyn )malloc(sizeof(Polyn));
(*P)->coef = 0.0;
(*P)->expn = 0;
(*P)->next = NULL;//初始化
}
void CreatPolyn(Polyn *P,int m)
{
float c;
int e,i;
Polyn s,q;
q = *P;
printf("请输入%d个项数\n",m);
for(i = 1;i<=m;i++)
{
printf("请输入第%d项的系数和指数: ",i);
scanf("%f %d",&c,&e);
s = (Polyn )malloc(sizeof(Polyn));
s->coef = c;
s->expn = e;
s->next = NULL;
q->next = s;
q = s;
q->next = NULL;
}
SortPolyn(*P);
}
void SortPolyn(Polyn P)
{
Polyn p,q,r;
q=P->next;
P->next=NULL;
while(q!=NULL) //插入法排序
{
p=P;
while(p->next!=NULL&&p->next->expn>q->expn)
p=p->next;
r=q->next;
q->next=p->next;
p->next=q;
q=r;
}
}
void ShowPolyn(Polyn P)
{
Polyn pchar;
pchar = P->next;
while(pchar)
{
printf("%fX^%d ",pchar->coef,pchar->expn);
pchar = pchar->next;
}
printf("\n");
}
void AddPolyn(Polyn Pa,Polyn Pb,Polyn Pc)
{
float x;
Polyn anext,bnext,q,s;
anext = Pa->next;
bnext = Pb->next;
q = Pc;
while(anext&&bnext)
{
if(anext->expn == bnext->expn)//指数相同
{
x = anext->coef+bnext->coef;
if(x!=0)//系数相加不等于0,插入表中
{
s = (Polyn)malloc(sizeof(Polyn));
s->coef = x;
s->expn = anext->expn;
s->next = NULL;
q->next = s;
q = q->next;
}
else//系数等于0
{
anext = anext->next;
bnext = bnext->next;
}
}
else if(anext->expn < bnext->expn)//指数小的插入表中
{
s = (Polyn)malloc(sizeof(Polyn));
s->coef = anext->coef;
s->expn = anext->expn;
s->next = NULL;
q->next = s;
q = q->next;
anext = anext->next;
}
else
{
s = (Polyn)malloc(sizeof(Polyn));
s->coef = bnext->coef;
s->expn = bnext->expn;
s->next = NULL;
q->next = s;
q = q->next;
bnext = bnext->next;
}
}
while(anext == NULL&&bnext!=NULL)
{
s = (Polyn)malloc(sizeof(Polyn));
s->coef = bnext->coef;
s->expn = bnext->expn;
s->next = NULL;
q->next = s;
q = q->next;
bnext = bnext->next;
}
while(bnext == NULL&&anext!=NULL)
{
s = (Polyn)malloc(sizeof(Polyn));
s->coef = anext->coef;
s->expn = anext->expn;
s->next = NULL;
q->next = s;
q = q->next;
anext = anext->next;
}
if(anext == NULL&&bnext == NULL)
{
printf("完成\n");
}
SortPolyn(q);
}
int main()
{
Polyn Pa,Pb,Pc;
InitPolyn(&Pa);
CreatPolyn(&Pa,3);
ShowPolyn(Pa);
InitPolyn(&Pb);
CreatPolyn(&Pb,2);
ShowPolyn(Pb);
InitPolyn(&Pc);
AddPolyn(Pa,Pb,Pc);
ShowPolyn(Pc);
}
|