直接法(高斯)求解線性方程組

#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;
}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章