一元多项式的加法。。给点意见哈。
#include<stdio.h>#include<stdlib.h>
typedef struct pnode{
float coef;//系数
int exp;//指数
struct pnode *next;
}pnode,*ploype;
void creatplo(ploype h,int n){
ploype p,q;
int i;
h=(ploype)malloc(sizeof(pnode));
h->next=NULL;
p=h;
printf("input the element's coef and exp:");
for(i=1;i<=n;i++){
q=(ploype)malloc(sizeof(pnode));
scanf("%f %d",&q->coef,&q->exp);
q->next=NULL;
p->next=q;
p=q;
}
}
int comp(int a,int b){
if(a<b) return -1;
if(a=b) return 0;
if(a>b) return 1;
}
void add(ploype pa,ploype pb,ploype pc){//?????
ploype p,q,pre,s;
int w;
float sum;
p=pa;
q=pb;
pre=pa; pc=pa;
while(p&&q){
w=comp(p->exp,q->exp);
switch(w){
case -1:p=p->next; break;
case 0: sum=p->coef+q->coef;
if(sum!=0){
p->coef=sum;
pre=p;
}
else{
pre->next=p->next;
free(q);
}
p=pre->next;
s=q;q=q->next;
free(s);
break;
case 1:s=q->next;q->next=p;
pre->next=q;
pre=q;
q=s; break;
}
}
if(pb) pre->next=q;
free(pb);
}
int main(){
ploype pa,pb,pc,p;
int n1,n2;
printf("input the lenght of pa,n1=");
scanf("%d",&n1);
printf("input the lenght of pb,n2=");
scanf("%d",&n2);
creatplo(pa,n1);
creatplo(pb,n2);
printf("caulate the result:");
add(pa,pb,pc);
p=pc->next;
printf("pc=pa+pb");
while(p!=NULL){
printf("%f,%d",p->coef,p->exp);
p=p->next;
}
return 0;
}
//最核心的add算法里,就是无法运算,对照了一下其他的代码,就是找不出错误,希望大家帮忙看看。。。谢谢了。