#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double **a = new double *[100];
int n,N;
cout<<"palease input the number of unkown variable and the number of equals:"<<endl;
cin>>n>>N;
double *x = new double[n+1];
double *tmp = new double[n+1]; //交换主元用
double m ;
//initialized the X and tmp
for(int i = 1; i <= n; i++ )
x[i] = 0;
for(i = 1; i <= n; i++)
tmp[i] = 0;
//create the equation set (A,b)
for(i = 1; i <= n;i++)
{
a[i] = new double[n+2];
for(int j = 1; j <= n+1; j++)
cin>>a[i][j];
}
//eliminate the equation set(n-1 times )
for(int k = 1; k < n; k++)
{
for(int t = k; t < n; t++)
{ int l = k;
for(int v = k; v <= n-1; v++)//从此处开始选择最佳的主元
{
if(fabs(a[v+1][k]) > fabs(a[v][k]))
l = v+1;
}
cout<<"l is "<<l<<endl;
for( v = k; v <= n+1; v++)
{
tmp[v] = a[k][v];
}
for(v = k; v <= n+1; v++)
{
a[k][v] = a[l][v];
}
for(v = k; v <= n+1; v++) //交换主元完毕
{
a[l][v] = tmp[v];
}
m = (1.0*a[t+1][k])/a[k][k];
cout<<"m is "<<m<<endl;
for(int i = 1; i <= n+1; i++)
{
a[t+1][i] = a[t+1][i] - m*a[k][i];
}
}
}
//iterate the equation set
x[n] = a[n][n+1]/a[n][n]; //求解Xn
for(i = n-1; i >= 1; i--)
{
double tmp = 0;
for(int j = i+1; j <= n; j++ )
{
tmp += a[i][j]*x[j];
}
x[i] = (a[i][n+1] - tmp)/a[i][i];
}
cout<<"the equation set is "<<endl;
for(i = 1; i <= n; i++)
{
for(int j = 1; j <= n+1; j++)
cout<<a[i][j];
cout<<endl;
}
cout<<"resulting is "<<endl;
//resulting....
for(i = 1; i <= n; i++)
{
cout<<"x is "<<x[i]<<endl;
}
return 0;
}
直接法(高斯)求解线性方程组
最新推荐文章于 2024-04-26 09:38:35 发布
该博客介绍了如何运用高斯消元法来求解线性方程组。首先,通过输入未知变量数量和等式数量初始化矩阵,接着进行主元选择和消除过程,最后迭代求解各个未知数的值。示例代码详细展示了整个计算流程。
摘要由CSDN通过智能技术生成