编程计算n+阶矩阵的行列式如果行列式非零求矩阵的逆矩阵。用C++代码写
#include
const int MAXN = 100; double a[MAXN][MAXN], b[MAXN][MAXN]; int n;
double det(double a[][MAXN], int n) { double ans = 1; for (int i = 0; i < n; i++) { int k = i; for (int j = i + 1; j < n; j++) if (fabs(a[j][i]) > fabs(a[k][i])) k = j; if (fabs(a[k][i]) < 1e-8) return 0; if (k != i) { for (int j = i; j < n; j++) swap(a[i][j], a[k][j]); ans = -ans; } ans *= a[i][i]; for (int j = i + 1; j < n; j++) a[i][j] /= a[i][i]; for (int j = 0; j < n; j++) if (j != i && fabs(a[j][i]) > 1e-8) for (int k = i + 1; k < n; k++) a[j][k] -= a[i][k] * a[j][i]; } return ans; }
bool inverse(double a[][MAXN], int n, double b[][MAXN]) { double detA = det(a, n); if (fabs(detA) < 1e-8) return false; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { b[i][j] = 0; for (int k = 0; k < n; k++) b[i][j] += a[k][i] * a[j][k]; b[i][j] /= detA; } } return true; }
int main() { cin >> n; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) cin >> a[i][j]; double detA = det(a, n); if (fabs(detA) < 1e-8) { cout << "The matrix is singular." << endl; return 0; } cout << "det(A) = " << detA << endl; if (inverse(a, n, b)) { cout << "A^-1 = " << endl; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << b[i][j] << " "; cout << endl; } } else { cout << "The matrix is singular." << endl; } return 0;
原文地址: https://www.cveoy.top/t/topic/cFhx 著作权归作者所有。请勿转载和采集!