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