高斯消元解n元一次方程

· · 个人记录

感谢 chatgpt 的贡献的核心代码

#include <bits/stdc++.h>
using namespace std;
int n;
double A[105][105], B[105];
// 高斯消元法求解线性方程组
void gaussElimination() {
    // 前向消元
    for (int i=0; i<n-1; i++) {
        for (int j=i+1; j<n; j++) {
            double ratio = A[j][i]/A[i][i];
            for (int k=i; k<n; k++) A[j][k] -= ratio*A[i][k];
            B[j] -= ratio*B[i];
        }
    }
    // 回代求解
    double X[105];
    memset(X,0,sizeof X);
    X[n-1] = B[n-1] / A[n-1][n-1];
    for (int i=n-2; i>=0; i--) {
        double sum=0;
        for (int j=i+1; j<n; j++) sum += A[i][j]*X[j];
        X[i]=(B[i]-sum)/A[i][i];
    }
    // 输出结果
    cout << "The solution is:\n";
    for (int i=0; i<n; i++) cout << X[i] << endl;
}
int main() {
    cout << "Enter the number of equations: ";
    cin >> n;
    // 输入系数矩阵A和常数矩阵B
    cout << "Enter the coefficient matrix A (" << n << "x" << n << "):\n";
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            cin >> A[i][j];
    cout << "Enter the constant matrix B (" << n << "x1):\n";
    for (int i = 0; i < n; i++) cin >> B[i];
    // 调用高斯消元法求解方程组
    gaussElimination();
    return 0;
}