voidgaussian_elimination(double a[N][N + 1], double *result) { for (int i = 0; i < N; i++) { // 找到主元 int max_row = i; for (int k = i + 1; k < N; k++) { if (abs(a[k][i]) > abs(a[max_row][i])) { max_row = k; } }
// 交换行 for (int k = i; k < N + 1; k++) { double tmp = a[i][k]; a[i][k] = a[max_row][k]; a[max_row][k] = tmp; }
// 消元 for (int k = i + 1; k < N; k++) { double factor = a[k][i] / a[i][i]; for (int j = i; j < N + 1; j++) { a[k][j] -= factor * a[i][j]; } } }
// 回代 for (int i = N - 1; i >= 0; i--) { result[i] = a[i][N]; for (int k = i + 1; k < N; k++) { result[i] -= a[i][k] * result[k]; } result[i] /= a[i][i]; } }