#include <iostream>using namespace std;//拉格朗日插值求解方程double * xs; //all input xdouble * ys; //all input yint n; //size//1.1275 1.1503 1.1735 1.1972//0.1191 0.13954 0.15932 0.17903//1.130void init(){cout << "please input n " << endl;cin >> n;xs = new double[n];ys = new double[n];//input xcout << "please input the x‘s value !" << endl;for(int i=0; i<n; i++){cin >> xs[i];}//input ycout << "please input the y‘s value !" << endl;for(int i=0; i<n; i++){cin >> ys[i];}}double everyItem(int num, double x){double y = ys[num];double up = 1;double down = 1;for(int i=0; i<n; i++){if(i != num){up *= (x - xs[i]);down *= (xs[num] - xs[i]);}}return y*up/down;}double lagrange(double x){double total = 0;for(int i=0; i<n; i++){total = total + everyItem(i , x);}return total;}int main(){init();double input;cout << "please input you x !" <<endl;cin >> input;double result = lagrange(input);cout << "the result is " << result << endl;return 0;}
原文:http://www.cnblogs.com/sober-reflection/p/28809f97512c2fa41aab75d0cb6866e6.html