主函数: // multinomial.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "stdio.h" #include "stdlib.h" #include "string.h" #include "E:/C_Data_Structures/Linear_List/multinomial/Horner.h" #include "E:/C_Data_Structures/Linear_List/multinomial/Polynomial.h" int _tmain(int argc, _TCHAR* argv[]) { _Horner(); Test_polynomail(); system("PAUSE"); return 0; } Horner头文件: #ifndef HORNER_H_INCLUDED #define HORNER_H_INCLUDED void Create_Horner(double *&a,int n) { a = (double*)calloc(n,sizeof(double)); if(!a) { fprintf(stderr,"Insufficient memory."); exit(EXIT_FAILURE); } for(--n;n >= 0;--n) { scanf("%lf",&a[n]); } } void Test_Horner(double *&a,int n,double &A) { double x; scanf("%lf",&x); while(n) { A = A*x + a[--n]; } //printf("%.2lf",A); free(a); a = NULL; } void _Horner() { int n; scanf("%d",&n); double *a = NULL,A = 0; Create_Horner(a,n); Test_Horner(a,n,A); printf("%.2lf",A); } #endif //测试数据 /* 3 2.11 3.21 4.15 1.11 */ polynomail头文件: #ifndef POLYNOMIAL_H_INCLUDED #define POLYNOMIAL_H_INCLUDED #define MAX_TERM 101 typedef struct { int expon; float coef; }polynomail; polynomail terms[MAX_TERM]; int avail = 0; typedef struct { int start,finish; }POL; void Creat_polynomail(POL &e) { scanf("%d%d",&e.start,&e.finish); int i = e.start,j = e.finish; while(i <= j) { scanf("%f%d",&terms[i].coef,&terms[i].expon); ++i; } avail = i; } void Print_polynomail(POL e) { while(e.start <= e.finish) { printf("%.2f*%d ",terms[e.start].coef,terms[e.start].expon); e.start++; } puts(""); } int compare(int a,int b) { int c = a - b; if(c < 0) { return -1; } else if(c == 0) { return 0; } else { return 1; } } void attach(float coefficient,int exponent) { if(avail >= MAX_TERM) { fprintf(stderr,"Too many terms in the polynomial."); exit(EXIT_FAILURE); } terms[avail].coef = coefficient; terms[avail++].expon = exponent; } void padd(POL A,POL B,POL &D) { D.start = avail; while(A.start <= A.finish && B.start <= B.finish) { switch(compare(terms[A.start].expon,terms[B.start].expon)) { case -1: attach(terms[B.start].coef,terms[B.start].expon); B.start++; break; case 0: attach(terms[B.start].coef + terms[A.start].coef,terms[B.start].expon); A.start++,B.start++; break; default: attach(terms[A.start].coef,terms[A.start].expon); A.start++; break; } } for(;A.start <= A.finish;A.start++) { attach(terms[A.start].coef,terms[A.start].expon); A.start++; } for(;B.start <= B.finish;B.start++) { attach(terms[B.start].coef,terms[B.start].expon); B.start++; } D.finish = avail - 1; } void Test_polynomail() { POL A,B,D; Creat_polynomail(A); Creat_polynomail(B); padd(A,B,D); Print_polynomail(D); } #endif /* 0 2 0.23 12 2.3 11 2 5 3 5 2.36 12 5.01 11 5.31 1 */