源之:
http://www.programfan.com/blog/article.asp?id=15604
#include <iostream>
using namespace std;
void main()
{
float **a,x,result;
int n,i;
float lglr(float **a,int n,float x);
cout<<"输入点数:";
cin>>n;
a=new float *[n];
for(i=0;i<n;i++)
a[i]=new float[2];
cout<<"输入各个点:"<<endl;
for(i=0;i<n;i++)
for(int j=0;j<2;j++)
cin>>a[i][j];
cout<<"输入自变量的值:";
cin>>x;
result=lglr(a,n,x);
cout<<"运算结果是:"<<result<<endl;
}
float lglr(float **a,int n,float x)
{
float result=0,xiang;
for(int i=0;i<n;i++)
{
xiang=a[i][1];
for(int j=0;j<n;j++)
if(j!=i)
xiang=xiang*(x-a[j][0])/(a[i][0]-a[j][0]);
result=result+xiang;
}
return result;
}
后来我有改进了一下写法,毕竟二次指针不是那么直观,改动如下:
#include <iostream>
using namespace std;
typedef struct {
float x; // first
float y; // second
}Cord;
float lglr(Cord *a , int n , float x )
{
float result = 0, xiang;
for(int i=0;i<n;i++)
{
xiang = a[i].y;
for(int j=0;j<n;j++)
if(j!=i)
xiang = xiang*(x-a[j].x)/(a[i].x-a[j].x);
result = result + xiang;
}
return result;
}
void main()
{
Cord *a ;
float x,result;
int n ,i;
cout<<"please input the numbers of coords:";
cin>>n;
a = new Cord[n];
cout<<"please input the coords:"<<endl;
for(int i=0;i<n;i++)
{
cin>>a[i].x;
cin>>a[i].y;
}
cout<<"please input the x"<<endl;
cin>>x;
result = lglr(a,n,x);
cout<<"the result of the lglr:"<<result;
delete[] a;
while(1)
{
}
}