满意答案
yydc1108gd
2014.05.17
采纳率:44% 等级:9
已帮助:4216人
#include
#include
#define epsilon 1e-6
void nihe1(int n,int m,float sum_x,float sum_y,float sum_xy,float x2);
void nihe2(int n,int m,float sum_x,float sum_y,float sum_xy,float x2,float x2y,float x3,float x4);
int main(){
float x[100]={0.0};
float y[100]={0.0};
int n,i,flag=1;
float sum_y=0.0,sum_x=0,x2=0,sum_xy=0.0,x3=0,x4=0,x2y=0.0;
printf("请你输入需要测试的数据(先输入x[],后输入y[])的个数:");
scanf("%d",&n);
for(i = 0; i < n; i++){
scanf("%f",&x[i]);}
for(i = 0; i < n; i++){
scanf("%f",&y[i]);}
for(i = 0; i < n; i++){
sum_x += x[i];
sum_y += y[i];
sum_xy += x[i]*y[i];
x2 += x[i]*x[i];
x2y += x[i]*x[i]*y[i];
x3 += x[i]*x[i]*x[i];
x4 += x[i]*x[i]*x[i]*x[i];}
printf("---------------请你输入的要拟合的函数------------------
");
printf(" 1、拟合一次函数
");
printf(" 2、拟合二次函数
");
scanf("%d",&flag);
switch(flag){
case 1:
nihe1(n,flag+1,sum_x,sum_y,sum_xy,x2); break;
case 2:
nihe2(n,flag+1,sum_x,sum_y,sum_xy,x2,x2y,x3,x4); break;
default:
printf("ERROR
");}
return 0;}
void nihe1(int n,int m,float sum_x,float sum_y,float sum_xy,float x2){
int i,k,j;
float t,s=0;
float a[2][3] = {{(float)n,sum_x,sum_y},{sum_x,x2,sum_xy}};
n=m;
//if(m == 3)
// a[3][4] = {{n,sum_x,sum_y},{sum_x,x2,x3,sum_xy},{x2,x3,x4,x2y}};
for(k=0;k
for(i=k+1;i
if( abs((int)a[i][k]) > abs((int)a[k][k]) )
for(j=k;j
t=a[k][j];
a[k][j]=a[i][j];
a[i][j]=t; }
if( abs((int)a[k][k]) < epsilon) {
printf("
Error,主元消去法 cann't be durable,break at %d!
",k+1);
return; }
for(i=k+1;i
a[i][k]=a[i][k] / a[k][k];
for(j=k+1;j
a[i][j]=a[i][j]-a[i][k] * a[k][j]; }}
a[n-1][n]=a[n-1][n] / a[n-1][n-1];
for(k=n-2;k>=0;k--) {
s=0;
for(j=k+1;j
s+=a[k][j]*a[j][n];
a[k][n]=( a[k][n]-s ) / a[k][k]; }
printf("
*****The Result*****
");
for(i=0;i
printf(" x[%d]=%.4f
",i+1,a[i][n]);
printf("函数为:p(x) = %.4f + (%.4f)*x
",a[0][n],a[1][n]);
getchar();}
void nihe2(int n,int m,float sum_x,float sum_y,float sum_xy,float x2,float x2y,float x3,float x4){
int i,k,j;
float t,s=0;
float a[3][4]=
{{(float)n,sum_x,x2,sum_y},{sum_x,x2,x3,sum_xy},{x2,x3,x4,x2y}};
n=m;
for(k=0;k
for(i=k+1;i
if( abs((int)a[i][k]) > abs((int)a[k][k]) )
for(j=k;j
t=a[k][j];
a[k][j]=a[i][j];
a[i][j]=t; }
if( abs((int)a[k][k]) < epsilon) {
printf("
Error,主元消去法 cann't be durable,break at %d!
",k+1);
return; }
for(i=k+1;i
a[i][k]=a[i][k] / a[k][k];
for(j=k+1;j
a[i][j]=a[i][j]-a[i][k] * a[k][j]; } }
a[n-1][n]=a[n-1][n] / a[n-1][n-1];
for(k=n-2;k>=0;k--) {
s=0;
for(j=k+1;j
s+=a[k][j]*a[j][n];
a[k][n]=( a[k][n]-s ) / a[k][k]; }
printf("
*****The Result*****
");
for(i=0;i
printf(" x[%d]=%.4f
",i+1,a[i][n]);
printf("函数为:p(x) = %.4f + (%.4f)*x + (%.4f)*x*x
",a[0][n],a[1][n],a[2][n]);
getchar();}
00分享举报