fatal.h
#include <stdio.h>
#include <stdlib.h>
#define Error( Str ) FatalError( Str )
#define FatalError( Str ) fprintf( stderr, "%s\n", Str ), exit( 1 )
poly.c
/* This code doesn't really do much */
/* Thus I haven't bothered testing it */
#include "fatal.h"
#define MaxDegree 100 // 幂的最大次数是100
static int
Max(int A, int B)
{
return A > B ? A : B;
}
/* START: fig3_18.txt */
typedef struct
{
int CoeffArray[MaxDegree + 1]; // 系数数组,这里定义了数组是很大的,所以下面要单独用一个HighPower来存最高次幂
int HighPower; // 高次幂
} *Polynomial;
/* END */
/* START: fig3_19.txt */
// 多项式初始化为零
void
ZeroPolynomial(Polynomial Poly)
{
int i;
for (i = 0; i <= MaxDegree; i++)
Poly->CoeffArray[i] = 0;
Poly->HighPower = 0;
}
/* END */
/* START: fig3_20.txt */
void
AddPolynomial(const Polynomial Poly1, const Polynomial Poly2,
Polynomial PolySum)
{
int i;
ZeroPolynomial(PolySum);
PolySum->HighPower = Max(Poly1->HighPower,
Poly2->HighPower);
for (i = PolySum->HighPower; i >= 0; i--)
PolySum->CoeffArray[i] = Poly1->CoeffArray[i]
+ Poly2->CoeffArray[i];
}
/* END */
/* START: fig3_21.txt */
void
MultPolynomial(const Polynomial Poly1,
const Polynomial Poly2, Polynomial PolyProd)
{
int i, j;
ZeroPolynomial(PolyProd);
PolyProd->HighPower = Poly1->HighPower + Poly2->HighPower;
if (PolyProd->HighPower > MaxDegree)
Error("Exceeded array size");
else
for (i = 0; i <= Poly1->HighPower; i++)
for (j = 0; j <= Poly2->HighPower; j++)
PolyProd->CoeffArray[i + j] +=
Poly1->CoeffArray[i] *
Poly2->CoeffArray[j];
}
/* END */
#if 0
/* START: fig3_23.txt */
typedef struct Node *PtrToNode;
struct Node
{
int Coefficient; // 系数
int Exponent; // 指数
PtrToNode Next;
};
typedef PtrToNode Polynomial; /* Nodes sorted by exponent */ // 按指数排序的节点
/* END */
#endif
void
PrintPoly(const Polynomial Q)
{
int i;
for (i = Q->HighPower; i > 0; i--)
printf("%dx^%d + ", Q->CoeffArray[i], i); // CoeffArray[i]代表系数,i代表指数
printf("%d\n", Q->CoeffArray[0]);
}
// 测试函数
int main()
{
Polynomial P, Q;
P = malloc(sizeof(*P));
Q = malloc(sizeof(*Q));
P->HighPower = 1;
P->CoeffArray[0] = 1;
P->CoeffArray[1] = 1; // P = x + 1
MultPolynomial(P, P, Q); // Q = P * P = x^2 + 2x + 1
MultPolynomial(Q, Q, P); // P = Q * Q = x^4 + 4x^3 + 6x^2 + 4x + 1
AddPolynomial(P, P, Q); // Q = P + P = 2x^4 + 8x^3 + 12x^2 + 8x^1 + 2
// 打印结果
PrintPoly(Q);
return 0;
}
输出结果:
注:书中页码:P39