编程计算n+阶矩阵的行列式,如果行列式非零,求矩阵的逆矩阵。用C++代码写
1个回答
关注
展开全部
以下是C++代码实现计算n阶矩阵行列式和求逆矩阵的过程:```cpp#include #include using namespace std;// 计算 n 阶矩阵 A 的行列式double det(vector A, int n) { double res = 1.0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { while (A[j][i] != 0) { double t = A[i][i] / A[j][i]; for (int k = i; k < n; k++) { A[i][k] -= t * A[j][k]; swap(A[i][k], A[j][k]); }
咨询记录 · 回答于2023-04-20
编程计算n+阶矩阵的行列式,如果行列式非零,求矩阵的逆矩阵。用C++代码写
以下是C++代码实现计算n阶矩阵行列式和求逆矩阵的过程:```cpp#include #include using namespace std;// 计算 n 阶矩阵 A 的行列式double det(vector A, int n) { double res = 1.0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { while (A[j][i] != 0) { double t = A[i][i] / A[j][i]; for (int k = i; k < n; k++) { A[i][k] -= t * A[j][k]; swap(A[i][k], A[j][k]); }
res = -res; } } if (A[i][i] == 0) { return 0; } res *= A[i][i]; } return res;}// 计算 n 阶单位矩阵vector eye(int n) { vector I(n, vector(n, 0)); for (int i = 0; i < n; i++) { I[i][i] = 1; } return I;}// 求 n 阶矩阵 A 的逆矩阵vector inv(vector A, int n) { vector I = eye(n); for (int i = 0; i < n; i++) {
double t = A[i][i]; for (int j = i; j < n; j++) { A[i][j] /= t; } for (int j = 0; j < n; j++) { I[i][j] /= t; } for (int j = 0; j < n; j++) { if (i != j) { double t = A[j][i]; for (int k = i; k < n; k++) { A[j][k] -= t * A[i][k]; } for (int k = 0; k < n; k++) { I[j][k] -= t * I[i][k]; }