C++程序计算矩阵行列式
方阵的行列式可以通过其元素值计算得出。矩阵A的行列式可以表示为det(A),在几何学中,它可以被称为矩阵所描述的线性变换的缩放因子。
以下是矩阵行列式的一个例子。
The matrix is: 3 1 2 7 The determinant of the above matrix = 7*3 - 2*1 = 21 - 2 = 19 So, the determinant is 19.
计算矩阵行列式的程序如下所示。
示例
#include<iostream>
#include<math.h>
using namespace std;
int determinant( int matrix[10][10], int n) {
int det = 0;
int submatrix[10][10];
if (n == 2)
return ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1]));
else {
for (int x = 0; x < n; x++) {
int subi = 0;
for (int i = 1; i < n; i++) {
int subj = 0;
for (int j = 0; j < n; j++) {
if (j == x)
continue;
submatrix[subi][subj] = matrix[i][j];
subj++;
}
subi++;
}
det = det + (pow(-1, x) * matrix[0][x] * determinant( submatrix, n - 1 ));
}
}
return det;
}
int main() {
int n, i, j;
int matrix[10][10];
cout << "Enter the size of the matrix:\n";
cin >> n;
cout << "Enter the elements of the matrix:\n";
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
cin >> matrix[i][j];
cout<<"The entered matrix is:"<<endl;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
cout << matrix[i][j] <<" ";
cout<<endl;
}
cout<<"Determinant of the matrix is "<< determinant(matrix, n);
return 0;
}输出
Enter the size of the matrix: 3 Enter the elements of the matrix: 7 1 3 2 4 1 1 5 1 The entered matrix is: 7 1 3 2 4 1 1 5 1 Determinant of the matrix is 10
在上面的程序中,矩阵的大小和元素在main()函数中提供。然后调用determinant()函数。它返回矩阵的行列式,并显示该值。这通过以下代码片段演示。
cout << "Enter the size of the matrix:\n";
cin >> n;
cout <<"Enter the elements of the matrix:\n";
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
cin >> matrix[i][j];
cout<<"The entered matrix is:"<<endl;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
cout << matrix[i][j] <<" ";
cout<<endl;
}
cout<<"Determinant of the matrix is "<< determinant(matrix, n);在determinant()函数中,如果矩阵的大小为2,则直接计算行列式并返回其值。这显示如下。
if (n == 2) return ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1]));
如果矩阵的大小不是2,则递归计算行列式。使用了3个嵌套的for循环,循环变量为x、i和j。这些循环用于计算行列式,并且递归调用determinant()函数来计算内部行列式,然后将其与外部值相乘。这通过以下代码片段演示。
for (int x = 0; x < n; x++) {
int subi = 0;
for (int i = 1; i < n; i++) {
int subj = 0;
for (int j = 0; j < n; j++) {
if (j == x)
continue;
submatrix[subi][subj] = matrix[i][j];
subj++;
}
subi++;
}
det = det + (pow(-1, x) * matrix[0][x] * determinant( submatrix, n - 1 ));
}
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP