#include
<
stdio.h
>
#include < conio.h >
#include < alloc.h >
float lagrange( float * x, float * y, float xx, int n) /* 拉格朗日插值算法 */
{ int i,j;
float * a,yy = 0.0 ; /* a作为临时变量,记录拉格朗日插值多项式 */
a = ( float * )malloc(n * sizeof ( float ));
for (i = 0 ;i <= n - 1 ;i ++ )
{ a[i] = y[i];
for (j = 0 ;j <= n - 1 ;j ++ )
if (j != i) a[i] *= (xx - x[j]) / (x[i] - x[j]);
yy += a[i];
}
free(a);
return yy;
}
main()
{ int i,n;
float x[ 20 ],y[ 20 ],xx,yy;
printf( " Input n: " );
scanf( " %d " , & n);
if (n >= 20 ) {printf( " Error!The value of n must in (0,20). " ); getch(); return 1 ;}
if (n <= 0 ) {printf( " Error! The value of n must in (0,20). " ); getch(); return 1 ;}
for (i = 0 ;i <= n - 1 ;i ++ )
{ printf( " x[%d]: " ,i);
scanf( " %f " , & x[i]);
}
printf( " /n " );
for (i = 0 ;i <= n - 1 ;i ++ )
{ printf( " y[%d]: " ,i);scanf( " %f " , & y[i]);}
printf( " /n " );
printf( " Input xx: " );
scanf( " %f " , & xx);
yy = lagrange(x,y,xx,n);
printf( " x=%f,y=%f/n " ,xx,yy);
getch();
}
#include < conio.h >
#include < alloc.h >
float lagrange( float * x, float * y, float xx, int n) /* 拉格朗日插值算法 */
{ int i,j;
float * a,yy = 0.0 ; /* a作为临时变量,记录拉格朗日插值多项式 */
a = ( float * )malloc(n * sizeof ( float ));
for (i = 0 ;i <= n - 1 ;i ++ )
{ a[i] = y[i];
for (j = 0 ;j <= n - 1 ;j ++ )
if (j != i) a[i] *= (xx - x[j]) / (x[i] - x[j]);
yy += a[i];
}
free(a);
return yy;
}
main()
{ int i,n;
float x[ 20 ],y[ 20 ],xx,yy;
printf( " Input n: " );
scanf( " %d " , & n);
if (n >= 20 ) {printf( " Error!The value of n must in (0,20). " ); getch(); return 1 ;}
if (n <= 0 ) {printf( " Error! The value of n must in (0,20). " ); getch(); return 1 ;}
for (i = 0 ;i <= n - 1 ;i ++ )
{ printf( " x[%d]: " ,i);
scanf( " %f " , & x[i]);
}
printf( " /n " );
for (i = 0 ;i <= n - 1 ;i ++ )
{ printf( " y[%d]: " ,i);scanf( " %f " , & y[i]);}
printf( " /n " );
printf( " Input xx: " );
scanf( " %f " , & xx);
yy = lagrange(x,y,xx,n);
printf( " x=%f,y=%f/n " ,xx,yy);
getch();
}