模板如下,复杂度O(n^3)
/* 高斯消元低精度版 @挠头小熊熊 * * 使用说明: * A为大小为n的增广矩阵,A[i][n]是第i个方程右边的常数bi * 运行后A[i][n]是第i个未知数的值 * 注意: * 函数第一个形参的第二维大小记得更改 * 本版精度不高 */ #include <cstdio> #include <algorithm> using namespace std; void gs(double A[][5], int n) { int i, j, k, r; for (i = 0; i < n; i++) { r = i; for (j = i + 1; j < n; j++) if (fabs(A[j][i]) > fabs(A[r][i])) r = j; if (r != i) for (j = 0; j <= n; j++) swap(A[r][j], A[i][j]); for (j = n; j >= i; j--) for (k = i + 1; k < n; k++) A[k][j] -= A[k][i] / A[i][i] * A[i][j]; } for (i = n - 1; i >= 0; i--) { for (j = i + 1; j < n; j++) A[i][n] -= A[j][n] * A[i][j]; A[i][n] /= A[i][i]; } } double A[][5] = {{2, 1, -1, 8}, { -3, -1, 2, -11}, { -2, 1, 2, -3}}; int main() { //freopen("in.in", "r", stdin); //freopen("out.out", "w", stdout); gs(A, 3); for (int i = 0; i < 3; i++) printf("%.3f\n", A[i][3]); return 0; }