求助下面程序求两个多项式的和哪里错了?
程序代码:
#include<stdio.h> #include<stdlib.h> #include<math.h> typedef struct Node //项的表示 { float coef; //系数 int exp; //指数 struct Node *next; //指向下一个节点 }LinkList; LinkList *PolyCreate() //尾插法建立多项式链表 { LinkList *L, *r, *s; float coef; int exp; L = (LinkList *)malloc(sizeof(LinkList)); r = L; scanf("%f,%d", &coef, &exp); while(fabs(coef) >= 1e-6) { s = (LinkList *)malloc(sizeof(LinkList)); s->coef = coef; s->exp = exp; r->next = s; r = s; scanf("%f,%d", &coef, &exp); } r->next = NULL; return L; } void PolyAdd(LinkList *p1, LinkList *p2) //多项式相加 { LinkList *p, *q, *r, *t; //t存放欲释放节点,r为链表的尾指针 float sum; p = p1->next; //p,q指向p1,p2第一个节点 q = p2->next; r = p1; while(p && q) { if(p->exp > q->exp) { r->next = q; q->next = p; r = q; q = q->next; } else if(p->exp < q->exp) { r = p; p = p->next; } else if(p->exp == q->exp) //指数相等时,系数相加 { sum = p->coef + q->coef; if(fabs(sum) > 1e-6) //系数相加不为0 { p->coef = sum; t = q; r = p; q = q->next; p = p->next; free(t); } else if(fabs(sum) <= 1e-6) //系数相加为0 { t = p; p = p->next; r->next = p; free(t); t = q; q = q->next; free(t); } } } if(q) r->next = q; free(p2); } void PrintPoly(LinkList *p1) //打印多项式 { LinkList *p; int i = 0; p = p1->next; while(p) { printf("<%7.2f, %5d> ", p->coef, p->exp); p = p->next; i++; if(i % 4 == 0) printf("\n"); } printf("\n多项式项数:\n", i); getchar(); } int main() { LinkList *pa, *pb; printf("Please enter pa's coef and exp:\n"); //输入多项式的系数和指数 pa = PolyCreate(); printf("Please enter pb's coef and exp:\n"); pb = PolyCreate(); PolyAdd(pa, pb); printf("print pa + pb :\n"); PrintPoly(pa); }
运行结果
[ 本帖最后由 无功 于 2015-4-13 13:30 编辑 ]