(1)、添加头文件Point.h
//point.h #include <iostream> using namespace std; class Point//Point类的声明 { public://外部接口 Point(double xx = 0,double yy = 0){X = xx;Y = yy;} double GetX() {return X;} double GetY() {return Y;} friend double linefit(Point l_point[], int n_point);//友元函数 //int型变量为点数 private: //私有数据成员 double X; double Y; }; //End of point.h(2)构造主函数
//main.cpp #include "stdafx.h" #include "Point.h" #include <iostream> #include <cmath> using namespace std; double linefit(Point l_point[], int n_point) //友元函数体 { double av_x,av_y; //声明变量 double L_xx,L_yy,L_xy; //变量初始化 av_x=0; //X的平均值 av_y=0; //Y的平均值 L_xx=0; //Lxx L_yy=0; //Lyy L_xy=0; //Lxy for(int i=0;i<n_point;i++) //计算X、Y的平均值 { av_x+=l_point[i].X/n_point; av_y+=l_point[i].Y/n_point; } for(int i=0;i<n_point;i++) //计算Lxx、Lyy和Lxy { L_xx+=(l_point[i].X-av_x)*(l_point[i].X-av_x); L_yy+=(l_point[i].Y-av_y)*(l_point[i].Y-av_y); L_xy+=(l_point[i].X-av_x)*(l_point[i].Y-av_y); } //cout<<"This line can be fitted by y=ax+b."<<endl; cout<<"a="<<L_xy/L_xx<<endl; //输出回归系数a cout<<"b="<<av_y-L_xy*av_x/L_xx<<endl; //输出回归系数b return double(L_xy/sqrt(L_xx*L_yy)); //返回相关系数r } int main() { Point l_p[7]={Point(19914.5,1781.0),Point(12520.1,1733.7), Point(25967.5,1822.2),Point(30643.4,1852.2), Point(36009.1,1887.3),Point(42080.3,1928.0),Point(51480.5,1988.7) };//初始化数据点 double r=linefit(l_p,7);//进行线性回归计算 //cout<<"Line coefficient r= "<<r<<endl;//输出相关系数 } 结果如下: