#include<iostream> #include<cmath> #include<vector> using namespace std; void func(float**p,float *q,float *r,int n) { //Gauss消元 int i,j,k,t; for(i = 0;i<n-1;i++) { //选主元模块 顺序gauss消元可不要 int tmp = i; float max = fabs(p[i][i]); for(t = i+1;t<n;t++) { if(fabs(p[t][i]) > max) tmp = t; } for(t = i;t<n;t++) { float tmp2 = p[i][t]; p[i][t] = p[tmp][t]; p[tmp][t] = tmp2; } float tmp3 = q[i]; q[i] = q[tmp]; q[tmp] = tmp3; if(p[i][i] == 0) { cout<<"gauss消元失败"<<endl; return; } //消元模块 for(j = i+1;j<n;j++) { for(k = i+1;k<n;k++) { p[j][k] = -p[j][i]*1.0/p[i][i]*p[i][k] + p[j][k]; } q[j] = -p[j][i]*1.0/p[i][i]*q[i] + q[j]; } } //回带模块 r[n-1] = q[n-1]*1.0/p[n-1][n-1]; for(i = n-2;i>=0;i--) { float tmp = 0.0; for(j = i+1;j<n;j++) { tmp+= p[i][j]*r[j]; } r[i] = (q[i]-tmp)*1.0/p[i][i]; } } int main() { int m; cout<<"输入拟合多项式的次数"<<endl; while(cin>>m && m != -1) { //m次多项式曲线 int sum = 0,i,j,k; cout<<"输入x和y的有序对 x=0&&y=0时输入结束"<<endl; vector<float>x,y; float x0,y0; while(cin>>x0>>y0 && !(x0 == 0 && y0 == 0)) { x.push_back(x0); y.push_back(y0); sum ++; } float **p = new float*[m+1]; float *q = new float[m+1]; float *r = new float[m+1]; for(i = 0;i<m+1;i++) p[i] = new float[m+1]; for(i = 0;i<m+1;i++) { for(j = 0;j<m+1;j++) { float tmp = 0.0; for(k = 0;k<sum;k++) { tmp += pow(x[k],i+j); } p[i][j] = tmp; } } for(i = 0;i<m+1;i++) { float tmp = 0.0; for(j = 0;j<sum;j++) { float tmp2 = pow(x[j],i); tmp += y[j]*tmp2; } q[i] = tmp; } cout<<m<<"次多项式系数为"<<endl; func(p,q,r,m+1); for(i = 0;i<m+1;i++) { cout<<r[i]<<" "; } cout<<endl; cout<<"输入拟合多项式的次数"<<endl; } return 0; }