使用C++编写牛顿插值法程序(可以输出差商表)
#include<iostream>
#include<cstdio>
using namespace std;
double aver(int num,double x[],double y[],double aa){
double a[num];
a[0]=y[0];
cout<<"下面输出差商表"<<"\n";
for (int i=1;i<=num-1;i++){
for (int j=0;j<num-i;j++){
double temp1=y[j];
double temp2=y[j+1];
y[j]=(temp2-temp1)/(x[j+i]-x[j]);
cout<<y[j]<<" ";
}
a[i]=y[0];
cout<<"\n"<<"\n";
}
double sum1=a[0];
for (int i=0;i<num-1;i++){
double sum2=1;
for (int j=0;j<=i;j++){
sum2=sum2*a[j+1]*(aa-x[j]);
}
sum1=sum1+sum2;
}
cout<<"下面输出计算值"<<"\n";
cout<<sum1;
}
int main(){
int num;
cout<<"输入节点的个数";
scanf("%d",&num);
double x[num],y[num];
for (int i=0;i<num;i++){
cout<<"输入第"<<i+1<<"个x的值";
scanf("%lf",&x[i]);
cout<<"输入第"<<i+1<<"个y的值";
scanf("%lf",&y[i]);
}
double aa;
cout<<"输入要计算的值";
cin>>aa;
cout<<"\n";
cout<<"下面输出插值节点表"<<"\n";
for (int i=0;i<num;i++){
cout<<x[i]<<" ";
}
cout<<"\n";
for (int i=0;i<num;i++){
cout<<y[i]<<" ";
}
cout<<"\n"<<"\n";
aver(num,x,y,aa);
return 0;
}