一元多项式(具有非负次幂)的数组实现
/* poly.h */ #ifndef _POLY_H #define _POLY_H #define MAXDEGREE 10 struct poly { int coefarray[MAXDEGREE + 1]; int highpower; }; void zero_poly(struct poly *p); void print_poly(const struct poly *p); void add_poly(const struct poly *p1, const struct poly *p2, struct poly *psum); void mult_poly(const struct poly *p1, const struct poly *p2, struct poly *pprod); #endif
/* poly.c */ #include "poly.h" #include <stdlib.h> #include <stdio.h> void zero_poly(struct poly *p) { int i; for( i = 0; i <= MAXDEGREE; i++) p->coefarray[i] = 0; p->highpower = 0; } void print_poly(const struct poly *p) { /* int i; for(i = p->highpower; i >= 0; i--) printf("%d ", p->coefarray[i]); printf("\n"); */ int i, hp; hp = p->highpower; if(p->coefarray[hp] != 1) printf("%dx^%d", p->coefarray[hp], hp); else printf("x^%d", hp); for(i = hp - 1; i >= 1; i--) { if(p->coefarray[i] != 0) { if(p->coefarray[i] != 1) printf(" + %dx^%d", p->coefarray[i], i);
else printf(" + x^%d", i); } } if(p->coefarray[0] != 0) printf(" + %d", p->coefarray[0]); printf("\n"); } void add_poly(const struct poly *p1, const struct poly *p2, struct poly *psum) { int i; int ph1, ph2; ph1 = p1->highpower; ph2 = p2->highpower; psum->highpower = ph1 > ph2 ? ph1 : ph2; for(i = psum->highpower; i >= 0; i--) { psum->coefarray[i] = p1->coefarray[i] + p2->coefarray[i]; } } void mult_poly(const struct poly *p1, const struct poly *p2, struct poly *pprod){ int i, j; zero_poly(pprod); pprod->highpower = p1->highpower + p2->highpower; if(pprod->highpower > MAXDEGREE) { printf("exceeded array size\n"); exit(1); } for(i = 0; i <= p1->highpower; i++) for(j = 0; j <= p2->highpower; j++) pprod->coefarray[i+j] += p1->coefarray[i] * p2->coefarray[j]; }
/* poly_test.c */ #include "poly.h" #include <stdio.h> int main(void) { struct poly p1, p2, psum, pmult; zero_poly(&p1); zero_poly(&p2); p1.highpower = 2; p1.coefarray[2] = 1; p2.highpower = 3; p2.coefarray[3] = 1; p2.coefarray[2] = 2; p2.coefarray[1] = 1; p2.coefarray[0] = 1; printf("p1 = "); print_poly(&p1); printf("p2 = "); print_poly(&p2); add_poly(&p1, &p2, &psum); printf("p1 + p2 = "); print_poly(&psum); mult_poly(&p1, &p2, &pmult); printf("p1 * p2 = "); print_poly(&pmult); }
运行结果如下: