求行列式

//用求上三角的方法求行列式的值

 

#include <cstdlib>
#include <iostream>

using namespace std;
int main(int argc, char *argv[])
{  
   
    //int a[n][n]={{1, 2, 3 ,4},{2 ,3 ,4 ,1},{3 ,4 ,1 ,2},{4, 1, 2, 3}};
    int n;
    freopen("data.txt","r",stdin);//请在工程项目目录下新建data.txt,将行列式的阶数及行列式信息输入

/*for example

3
1 2 -3
-2 3 -1
1 -2 8

*/
    freopen("res.txt","w",stdout);//结果输出
    cin>>n;
    double a[n][n];
    for(int i=0;i<n;i++)
    for(int j=0;j<n;j++)
    cin>>a[i][j];
    int sign=1;
    double tmp[n];
    int p;
    for(int col=0;col<n;col++)
    {
       int row;
       p=-1;   
       for(row=col;row<n;row++)
       {
          if(a[row][col]!=0)
          {
           p=row; break;                  //确保当前的值不为零,否则下面将出现错误,算法要求出右下的不为零的点
          }                         
       }
       if(-1==p) {cout<<"0"<<endl;return 0;}
       if(p!=col) //交换
       {
         for(int j=0;j<n;j++)
         {
            tmp[j]=a[col][j];
            a[col][j]=a[p][j];
            a[p][j]=tmp[j];            
         }
         sign=-sign;        // 交换变号
       }
      
       for(int row=col+1;row<n;row++)
       {
         double factor=a[row][col]/a[col][col];//确保a[col][col]不为零    
         a[row][col]=0;          
         for(int _col=col+1;_col<n;_col++)
         {
          a[row][_col]-=a[col][_col]*factor;      
         }
       }
       for(int i=0;i<n;i++)
       {
       for(int j=0;j<n;j++)
       cout<<a[i][j]<<" ";
       cout<<endl;
       }
       cout<<endl;           
    }
    double res=1.0;
    for(int i=0;i<n;i++)
    {      
    res*=a[i][i];
    }
    cout<<endl;
    res*=sign;
    cout<<res<<endl;
   
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值