关于多项式的加法,错在哪里呢?诚问。
显示的系数总是为0,多项式和为zero item。我是新手,虚心求教程序代码:
#include <stdio.h> #include <stdlib.h> typedef struct polynomials { int coef; int exp; struct polynomials *next; }poly; poly *create(){ int n; poly *head; poly *p1,*p2; n=0; p1=p2=(poly*)malloc(sizeof(poly)); scanf("%d%d",&p1->coef,&p1->exp); if(p1->next==0)head=NULL; else { while(p1->coef!=0) {n++; if(n==1)head=p1; else p2->next=p1; p2=p1; scanf("%d%d",&p1->coef,&p1->exp); } p2->next=NULL; } return head; } void print(poly *p){ poly *q; q=p; printf(" "); if(q!=0) do { printf("%dX^%d",q->coef,q->exp); q=q->next; if(q!=0)printf("+"); }while(q!=0); else printf("zero item"); printf("\n"); } int compare(poly *a,poly *b){ if(a->exp>b->exp)return 1; else if(a->exp<b->exp)return -1; return 0; } poly *add(poly *a,poly *b){ poly *head,*polya=a,*polyb=b,*p,*q; int sum; head=p=(poly*)malloc(sizeof(poly)); p->next=NULL; while(polya&&polyb){ switch(compare(polya,polyb)){ case -1: p->next=polyb; p=polyb; polyb=polyb->next; break; case 0: sum=polya->coef+polyb->coef; if(sum!=0){ polya->coef=sum; p->next=polya; p=polya; polya=polya->next; } else{ q=polya; polya=polya->next; free(q); } q=polyb; polyb=polyb->next; free(q); break; case 1: p=polya->next; p=polya; polya=polya->next; break; } } if(polya)p->next=polya; if(polyb)p->next=polyb; q=head; head=head->next; free(q); return head; } int main(){ poly *a,*b,*s; printf("input polynomials a: "); a=create(); printf("input polynomials b: "); b=create(); printf("poly_a:\n"); print(a); printf("poly_b:\n"); print(b); printf("poly_sum:\n"); s=add(a,b); print(s); }
[ 本帖最后由 ste11ar 于 2009-9-26 13:26 编辑 ]