高斯消元法求解线性方程组

#include <iostream>

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 m ;
  //initialized the X
  for(int i = 1; i <= n; i++ )
       x[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++)
	{
	  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;
  }
  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;
}






posted on 2013-11-01 19:22  you Richer  阅读(286)  评论(0编辑  收藏  举报