列主元消元法

来源:互联网 发布:模拟人生4mac怎么放mod 编辑:程序博客网 时间:2024/04/30 20:53

#include<iostream>

#include<iomanip>

#include<fstream>

using namespace std;

ifstream in("a.txt");

/*4

1.116      0.1254    0.1397    0.1490    1.5471

0.1582    1.1675    0.1768    0.1871    1.6471

0.1968    0.2071    1.2168    0.2271    1.7471

0.2368    0.2471    0.2568    1.2671    1.8471*/

typedef struct node

{

       double arr[30][30];

       int n;

}type;

void print(type t)

{

       int i,j;

       for(i=0;i<t.n;++i)

       {

              for(j=0;j<=t.n;++j)

                     cout<<setw(9)<<t.arr[i][j] ;

              cout<<endl;

       }

}

void input(type&t)

{

       int i,j;

       in>>t.n;

       for(i=0;i<t.n;++i)

       {

              for(j=0;j<=t.n;++j)

                     in>>t.arr[i][j];

       }

}

double abs(double n)

{

       return n>0 ? n:-n;

}

void Find_Max(type&t,int r)

{

       int i,u=r;double max=abs(t.arr[r][r]);

       for(i=r+1;i<t.n;++i)

       {

              if(abs(t.arr[i][r])>max)

              {

                     max=abs(t.arr[i][r]);

                     u=i;

              }

       }

       double temp;

       for(i=0;i<=t.n;++i)

       {

              temp=t.arr[r][i];

              t.arr[r][i]=t.arr[u][i];

              t.arr[u][i]=temp;

       }

}

void kk(type&t,int r)

{

       int i,j;double tt[20];

       for(i=r+1;i<t.n;++i)

       {

              for(j=0;j<=t.n;++j)

                     tt[j]=-(t.arr[i][r]*t.arr[r][j])/t.arr[r][r];

              for(j=0;j<=t.n;++j)

                     t.arr[i][j]+=tt[j];

       }

}

int main()

{

       int i,j;

       type t;input(t);

       for( i=0;i<t.n;++i)

       {

              Find_Max(t,i);kk(t,i);

       }

       print(t);

       double x[20];

       double temp;

       for(i=t.n-1;i>=0;--i)

       {

              temp=0;

              for(j=i+1;j<t.n;++j)

              {

                     temp+=t.arr[i][j]*x[j];

              }

              x[i]=(t.arr[i][t.n]-temp)/t.arr[i][i];

               

       }

       for(i=0;i<=t.n-1;++i)

              cout<<x[i]<<" ";

       cout<<endl;

      

       return 0;

}

 

原创粉丝点击