两种求矩阵行列式的方法。
方法一:
#include<iostream>
#include <iomanip>
using namespace std;
#define N 3 //矩阵维数,提前设置好double fun(double array[N][N]);
void temp(double aa[],double bb[],int n); int main()
{ double a[N][N] = {{10.2,5.8,3.2}, {1,8,9}, {10,15,9.6}};double det;int i,j,kk=0;char flag;cout<<"Press Y to input your specific array, or press N to test our default array."<<endl;cout<<"Press Y/N"<<endl;cin>>flag;if(flag == 'Y'){double a[N][N]; cout<<"请输入一个"<<N<<"维方阵"<<endl; for(i=0; i<N; i++) //一个矩阵的输入 for(j=0; j<N; j++) cin>>a[i][j];}else if(flag != 'Y' && flag != 'N'){cout<<"Wrong input!"<<endl;system("pause");return 0;}det = fun(a); //获取行列式的值 cout<<"矩阵的行列式的值为:"<<det<<endl; cout<<"转换的上三角矩阵为:"<<endl; for(i=0; i<N; i++) for(j=0; j<N; j++) { cout<<setw(7)<<a[i][j]; kk = kk + 1; if( kk % N == 0 ) cout<<endl; }cout<<endl;system("pause");return 0;
}//交换数组指定的两行,即进行行变换(具体为行交换)
void temp(double aa[],double bb[],int n)
{int i;double temp1;for(i=0 ; i<n ; i++){temp1 = aa[i];aa[i] = bb[i];bb[i] = temp1;}
}double fun(double array[N][N])
{int ii,jj,k,u; int iter = 0; //记录行变换的次数(交换)double det1=1,yin; for(ii=0; ii<N; ii++) {if(array[ii][ii] == 0)for(jj=ii; jj<N; jj++){if(array[jj][ii] != 0){temp(array[ii],array[jj],N);//交换两行iter ++;}}for(k=ii+1; k<N; k++) { yin = -1 * array[k][ii] / array[ii][ii] ; for(u=0; u<N; u++) { array[k][u] = array[k][u] + array[ii][u] * yin; }}}for(ii=0; ii<N; ii++) //求对角线的积 即 行列式的值det1 = det1 * array[ii][ii];//行变换偶数次符号不变if(iter%2 == 1)det1= -det1;return (det1);
}
方法二:
#include<iostream>
#include <iomanip>
using namespace std; float fun(float **_Array, int n)
{int iter = 0; //记录行变换的次数(交换)float det1=1,yin, temp0; for(int ii=0; ii<n; ii++) {if(_Array[ii][ii] == 0)for(int jj=ii; jj<n; jj++){if(_Array[jj][ii] != 0){for(int k = 0; k<n; k++){temp0 = _Array[ii][k];_Array[ii][k] = _Array[jj][k];_Array[jj][k] = temp0;}iter ++;}}for(int k=ii+1; k<n; k++) { yin = -1 * _Array[k][ii] / _Array[ii][ii] ; for(int u=0; u<n; u++) { _Array[k][u] = _Array[k][u] + _Array[ii][u] * yin; }}}for(int ii=0; ii<n; ii++) //求对角线的积 即 行列式的值det1 = det1 * _Array[ii][ii];//行变换偶数次符号不变if(iter%2 == 1)det1= -det1;return (det1);
}int main()
{ int dimension_Num = 3; float **Array = new float*[dimension_Num];for(int i = 0; i<dimension_Num; i++)Array[i] = new float[dimension_Num];Array[0][0] = 1;Array[0][1] = 2;Array[0][2] = 4;Array[1][0] = 8;Array[1][1] = 10;Array[1][2] = 2;Array[2][0] = 4;Array[2][1] = 2;Array[2][2] = 10;for(int i = 0; i<dimension_Num; i++){for(int j = 0; j<dimension_Num; j++)cout<< Array[i][j]<<" ";cout<<endl;}float det;if(dimension_Num == 1)det = Array[0][0];else if(dimension_Num == 2)det = Array[0][0] * Array[1][1] - Array[0][1] * Array[1][0] ;elsedet = fun(Array,dimension_Num);cout<<"矩阵的行列式的值为:"<<det<<endl; cout<<"转换的上三角矩阵为:"<<endl; for(int i=0; i<dimension_Num; i++) {for(int j=0; j<dimension_Num; j++) cout<<Array[i][j]<<" "; cout<<endl; }cout<<endl;system("pause");return 0;
}
本文链接:https://my.lmcjl.com/post/13856.html
展开阅读全文
4 评论