📄 newton.c
字号:
////////////////////////////////////////////////////////
// (x_i,y_i)的牛顿插值多项式 //
////////////////////////////////////////////////////////
#include <stdio.h>
#define MAX_N 20 //定义(x_i,y_i)的最大维数
typedef struct tagPOINT //定义点的结构
{
double x;
double y;
} POINT;
int main()
{
int n, i, j;
POINT points[MAX_N+1];
double diff[MAX_N+1];
double x, tmp, newton;
char c;
printf("\nInput n value: "); //输入被插值点的数目
scanf("%d",&n);
if (n > MAX_N)
{
printf("The input is larger than MAX_N, please redefine the MAX_N. \n");
return 1;
}
if (n <= 0)
{
printf("Please input a number between 1 and %d. \n", MAX_N );
return 1;
}
//输入被插值点(x_i,y_i)
printf("Now input the (x_i,y_i),i=0,...,%d: \n", n);
for(i = 0; i <= n; i++)
scanf("%lf %lf", &points[i].x, &points[i].y);
for(i = 0; i <= n; i++) diff[i] = points[i].y;
for(i = 0; i < n; i++ )
{
for (j = n; j > i; j--)
//计算f(x_0,..,x_n)的插商
diff[j] = (diff[j] - diff[j-1])/(points[j].x - points[j-1-i].x);
}
while(1)
{
printf("Do you want to continue the calculation? 'y' or 'n'? : ");
getchar(); //先把缓冲区的字符读出,防止出错
c = getchar(); //然后再接受用户的输入
switch(c)
{
case 'y':
{
printf("\nNow input the x value: "); //输入计算牛顿插值多项式的x值
scanf("%lf", &x);
tmp = 1;
newton = diff[0];
for(i = 0; i < n; i++)
{
tmp = tmp * (x - points[i].x);
newton = newton + tmp * diff[i+1];
}
printf("newton(%f) = %f\n", x, newton); //输出结果
break;
}
case 'n':
{
printf("Thank you for using, goodbye.\n");
return 0;
}
default:
{
printf("\nPlesae press y or n to choose! \n");
break;
}
}
}
}
/*
if(c == 'n')
{
printf("Thank you for using, goodbye.\n");
return 0;
}
else if(c == 'y')
{
printf("Now input the x value: "); //输入计算牛顿插值多项式的x值
scanf("%lf", &x);
for(i = 0; i <= n; i++) diff[i] = points[i].y;
for(i = 0; i < n; i++ )
{
for (j = n; j > i; j--)
//计算f(x_0,..,x_n)的插商
diff[j] = (diff[j] - diff[j-1])/(points[j].x - points[j-1-i].x);
}
tmp = 1;
newton = diff[0];
for(i = 0; i < n; i++)
{
tmp = tmp * (x - points[i].x);
newton = newton + tmp * diff[i+1];
}
printf("newton(%f) = %f\n", x, newton); //输出结果
return 0;
}
else
{
printf("Plesae press y or n to choose! \n");
continue;
}*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -