#include <stdio.h>
#define _PARAM (5)
/*
原方程:5元1次方程组
(1): a0*X1 + b0*X2 + c0*X3 + d0*X4 + e0*X5 = f0
(2): a1*X1 + b1*X2 + c1*X3 + d1*X4 + e1*X5 = f1
(3): a2*X1 + b2*X2 + c2*X3 + d2*X4 + e2*X5 = f2
(4): a3*X1 + b3*X2 + c3*X3 + d3*X4 + e3*X5 = f3
(5): a4*X1 + b4*X2 + c4*X3 + d4*X4 + e4*X5 = f4
第一步:消除未知数 X1
(2) * a0 / a1 - (1) 得4元1次方程组
(1): (b1 * (a0/a1) - b0)*X2 + (c1 * (a0/a1) - c0)*X3 + (d1 * (a0/a1) - d0)*X4 + (e1 * (a0/a1) - e0)*X2 = f1 * (a0/a1) - f0
(2): (b2 * (a0/a2) - b0)*X2 + (c2 * (a0/a2) - c0)*X3 + (d2 * (a0/a2) - d0)*X4 + (e2 * (a0/a2) - e0)*X2 = f2 * (a0/a2) - f0
(3): (b3 * (a0/a3) - b0)*X2 + (c3 * (a0/a3) - c0)*X3 + (d3 * (a0/a3) - d0)*X4 + (e3 * (a0/a3) - e0)*X2 = f3 * (a0/a3) - f0
(4): (b4 * (a0/a4) - b0)*X2 + (c4 * (a0/a4) - c0)*X3 + (d4 * (a0/a4) - d0)*X4 + (e4 * (a0/a4) - e0)*X2 = f4 * (a0/a4) - f0
第二步: 同理消除未知数 X2
.....
最后只剩未知数 X4 = n 一元一次方程
第三步:将求得的X4,一步一步回代,分别求出X3,X2,X1,X0
*/
int main()
{
int i,j,k;
int n = _PARAM;
double temp = 0;
double param[_PARAM][_PARAM+1] =
{
{101,97,86,74,55,145},
{86,79,123,119,87,117},
{96,129,136,97,64,92},
{158,201,158,124,131,224},
{76,102,95,53,111,135}
};
double parameter[_PARAM][_PARAM+1];
double Result_x[_PARAM] ={0};
for(i=0 ; i<n ; i++)
{
for(j=0; j<=n ; j++)
{
parameter[i][j] = param[i][j];
}
}
//消元
for(i=0; i<n; i++)
{
for(j=i ; j<n ; j++)
{
for(k=i+1; k<=n; k++)
{
parameter[j][k] /= parameter[j][i];
if(j > i)
{
parameter[j][k] -= parameter[i][k];
}
}
}
}
//回代
for(i=n-1; i>=0 ; i--)
{
temp = 0.0;
for(j=n-1 ; j>i; j--)
{
temp += Result_x[j] * parameter[i][j];
}
Result_x[i] = parameter[i][n] - temp;
}
//输出结果及验算
for(i=0 ; i<n ; i++)
{
printf("X%d=%f,",i,Result_x[i]);
temp = 0;
for(j=0 ; j<n ; j++)
{
temp = temp + param[i][j] * Result_x[j];
}
//temp = 0 证明解正确
temp -= param[i][j];
printf("temp=%f\n",temp);
}
return 0;
}
|