要求:能够按照指数降序排列建立并输出多项式;能够完成两个多项式的相加、相减,并将结果输出。
大家帮忙看看这个程序的对错,谢谢~~~
#include<stdio.h>
#include<malloc.h>
typedef struct{
float coef;
int expn;
}Elemtype;
typedef struct node{
Elemtype date;
struct node* next;
}node,*polynomial;
void Initpoly(polynomial &p)
{
p=(polynomial)malloc(sizeof(node));
p->date.expn=0;
p->date.coef=0.0;
p->next=NULL;
} //初始化链表
int cmp(Elemtype a1,Elemtype a2)
{
if(a1.expn>a2.expn)return 1;
if(a1.expn<a2.expn)return -1;
else return 0;
}//比较两个结点
void Insertpoly(polynomial p1,Elemtype e)
{
polynomial p=p1,pnew;
pnew=(polynomial)malloc(sizeof(node));
while(p->next!=NULL)
{
if(cmp(p->next->date,e)==-1) p=p->next;
else break;
}
pnew->date=e;
pnew->next=NULL;
if(cmp(p->date,e)==0)p->date.coef+=e.coef;
else
{
pnew->next=p->next;p->next=pnew;
}
}//按序插入结点
void Creatpoly(polynomial & poly)
{
static int i=1;
Elemtype e;
printf("请输入第%d个多项式的系数与指数 以 系数 指数的形式输入\n",i);
scanf("%f %d",&e.coef,&e.expn);
Initpoly(poly);
while(e.coef!=0||e.expn!=0)
{
Insertpoly(poly,e);
scanf("%f %d",&e.coef,&e.expn);
}
i++;
}//创造一个链表
void Appendpoly(polynomial &p1,polynomial &p2)
{
polynomial p=p1;
while(p->next!=NULL)
{p=p->next;}
p->next=p2;
}//两个链表相接
void Addpoly(polynomial p1,polynomial p2)
{
polynomial p=p1->next,h=p2->next;
while(p!=NULL&&h!=NULL)
{
switch(cmp(p->date,h->date))
{
case 1:
{
Insertpoly(p1,h->date);
h=h->next;
break;
}
case 0:
{
p->date.coef+=h->date.coef;
p=p->next;h=h->next;
break;
}
case -1:
{
Insertpoly(p,h->date);
h=h->next;
p=p->next;
break;
}
}
}
if(h!=NULL)Appendpoly(p1,h);
printf("两个多项式的和为:\n");
}//两个多项式相加
void Destroypoly(polynomial p)
{
while(p!=NULL)
{
polynomial p1=p;
p=p->next;
free(p1);
}
}//释放存储空间
void Printpoly(polynomial p)
{
polynomial p1=p->next;
printf("(%f %d)",p1->date.coef,p1->date.expn);
p1=p1->next;
while(p1!=NULL)
{
printf("+(%f %d)",p1->date.coef,p1->date.expn);
p1=p1->next;
}
printf("\n");
}//打印多项式
void main()
{
polynomial p1;
Creatpoly(p1);
Printpoly(p1);
polynomial p2;
Creatpoly(p2);
Printpoly(p2);
Addpoly(p1,p2);
Printpoly(p1);
Destroypoly(p2);
Destroypoly(p1);
}
大家有没有更简单的方法 谢谢阿!~