关于“链式存储结构实现一元多项式的相加运算”的问题,请大神指教
代码.rar
(1.28 KB)
检测的时候没错,但有些功能运行不了
应该怎么改,求指教#include<stdio.h>#include<stdlib.h>
typedef struct pnode
{
int exp;
float coef;
struct pnode *next;
}polynode;
polynode *A,*B,*C,*D;
polynode *creatA()
{
polynode *p1,*r;
int i,n;
A=(polynode*)malloc(sizeof(polynode));
A->next=NULL;
r=A;
printf("请输入A多项式的项数:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
p1=(polynode*)malloc(sizeof(polynode));
printf("请输入A的第i项的系数和指数:",i);
scanf("%f%d",&p1->coef,&p1->exp);
r->next=p1;
r=p1;
}
r->next=NULL;
return A;
}
polynode *creatB()
{
polynode *p2,*r;
int i,n;
B=(polynode*)malloc(sizeof(polynode));
B->next=NULL;
r=B;
printf("请输入B多项式的项数:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
p2=(polynode*)malloc(sizeof(polynode));
printf("请输入B的第i项的系数和指数:",i);
scanf("%f%d",&p2->coef,&p2->exp);
r->next=p2;
r=p2;
}
r->next=NULL;
return B;
}
void printA(polynode *A)
{
polynode *p1;
p1=A->next;
while(p1->next!=NULL)
{
if(p1->next->coef>0)
printf("%.2fx^%d+",p1->coef,p1->exp);
else
printf("%.2fx^%d",p1->coef,p1->exp);
p1=p1->next;
}
printf("%.2fx^%d",p1->coef,p1->exp);
}
void printB(polynode *B)
{
polynode *p2;
p2=B->next;
while(p2->next!=NULL)
{
if(p2->next->coef>0)
printf("%.2fx^%d+",p2->coef,p2->exp);
else
printf("%.2fx^%d",p2->coef,p2->exp);
p2=p2->next;
}
printf("%.2fx^%d",p2->coef,p2->exp);
}
void printC(polynode *C)
{
polynode *p=C->next;
while(p->next!=NULL)
{
if(p->next->coef>0)
printf("%.2fx^%d+",p->coef,p->exp);
else
printf("%.2fx^%d",p->coef,p->exp);
p=p->next;
}
printf("%.2fx^%d",p->coef,p->exp);
}
polynode *polyadd(polynode *A,polynode *B)
{
polynode *p1,*p2,*p,*C;
float x;
p1=A->next;
p2=B->next;
p=(polynode*)malloc(sizeof(polynode));
p->next=NULL;
C=p;
while(p1&&p2)
{
if(p1->exp==p2->exp)
{
x=p1->coef+p2->coef;
if(x!=0)
{
p->next=(polynode*)malloc(sizeof(polynode));
p=p->next;
p->coef=x;
p->exp=p1->exp;
}
p1=p1->next;
p2=p2->next;
}
else
{
p->next=(polynode*)malloc(sizeof(polynode));
p=p->next;
if(p1->exp>p2->exp)
{
p->coef=p2->coef;
p->exp=p2->exp;
p2=p2->next;
}
else
{
p->coef=p1->coef;
p->exp=p1->exp;
p1=p1->next;
}
}
}
while(p1!=NULL)
{
p->next=(polynode*)malloc(sizeof(polynode));
p=p->next;
p->coef=p1->coef;
p->exp=p1->exp;
p1=p1->next;
}
while(p2!=NULL)
{
p->next=(polynode*)malloc(sizeof(polynode));
p=p->next;
p->coef=p2->coef;
p->exp=p2->exp;
p2=p2->next;
}
p->next=NULL;
return C;
}
int main()
{
polynode *p1,*p2,*p;
int i;
while(i)
{
printf("\t\t0:创建多项式A\n\t\t1:创建多项式B\n\t\t2:多项式A与多项式B相加\n\t\t3:输出多项式A\n\t\t4:输出多项式B\n\t\t5:输出相加后的多项式C\n");
scanf("%d",&i);
switch(i)
{
case 0:creatA();break;
case 1:creatB();break;
case 2:p=polyadd(A,B);break;
case 3:printA(A);break;
case 4:printB(B);break;
case 5:printC(p);break;
}
printf("\n\t\t0:结束\n\t\t1:继续\n");
scanf("%d",&i);
}
}
[ 本帖最后由 c语言新手yu 于 2014-1-2 00:41 编辑 ]