首页 > 代码库 > 数组实现多项式的加减乘运算

数组实现多项式的加减乘运算

"fatal.h"//头文件
1 #include<stdio.h>
2 #include<stdlib.h>
3 #define Error(Str) FatalError(Str)
4 #define FatalError(Str) fprintf(stderr,"%s\n",Str),exit(1);

1
/* This code doesn‘t really do much */ 2 /* Thus I haven‘t bothered testing it */ 3 4 #include "fatal.h"//头文件 5 6 #define MaxDegree 100//定义多项式最大指数是100 7 8 static int 9 Max( int A, int B ) 10 { 11 return A > B ? A : B;//返回AB中的最大值 12 } 13 //定义一个结构体数组 15 typedef struct 16 { 17 int CoeffArray[ MaxDegree + 1 ];//需要多存储一个常数项 18 int HighPower;//存储多项式的最高项的指数 19 } *Polynomial; 20 /* END */ 21 22 /* START: fig3_19.txt */ 23 void 24 ZeroPolynomial( Polynomial Poly )//初始化多项式 25 { 26 int i; 27 28 for( i = 0; i <= MaxDegree; i++ ) 29 Poly->CoeffArray[ i ] = 0; 30 Poly->HighPower = 0; 31 } 32 /* END */ 33 34 /* START: fig3_20.txt */ 35 void //两个多项式相加 36 AddPolynomial( const Polynomial Poly1, const Polynomial Poly2, 37 Polynomial PolySum ) 38 { 39 int i; 40 41 ZeroPolynomial( PolySum ); 42 PolySum->HighPower = Max( Poly1->HighPower, 43 Poly2->HighPower ); 44 45 for( i = PolySum->HighPower; i >= 0; i-- ) 46 PolySum->CoeffArray[ i ] = Poly1->CoeffArray[ i ] 47 + Poly2->CoeffArray[ i ]; 48 } 49 /* END */ 50 51 /* START: fig3_21.txt */ 52 void //两个多项式相乘 53 MultPolynomial( const Polynomial Poly1, 54 const Polynomial Poly2, Polynomial PolyProd ) 55 { 56 int i, j; 57 58 ZeroPolynomial( PolyProd ); 59 PolyProd->HighPower = Poly1->HighPower + Poly2->HighPower; 60 61 if( PolyProd->HighPower > MaxDegree ) 62 Error( "Exceeded array size" ); 63 else 64 for( i = 0; i <= Poly1->HighPower; i++ ) 65 for( j = 0; j <= Poly2->HighPower; j++ ) 66 PolyProd->CoeffArray[ i + j ] += 67 Poly1->CoeffArray[ i ] * 68 Poly2->CoeffArray[ j ]; 69 } 70 /* END */

数组实现多项式的加减乘运算