直接法(高斯)求解线性方程组

该博客介绍了如何运用高斯消元法来求解线性方程组。首先,通过输入未知变量数量和等式数量初始化矩阵,接着进行主元选择和消除过程,最后迭代求解各个未知数的值。示例代码详细展示了整个计算流程。
摘要由CSDN通过智能技术生成
#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;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值