【C++】高斯消去法

#include <iostream>
using namespace std;
int main(){
    int n = 3;
    int m = n+1;
    double a[n][m];
    for(int i=0; i<n; i++)
        for(int j=0; j<m; j++)
            cin >> a[i][j];
    for(int i=0; i<n-1; i++){
        if(a[i][i] == 0){
            int t = 1;
            while(a[i+t][i] == 0) t++;
            for(int k=0; k<m; k++){
                double temp = a[i][k];
                a[i][k] = a[i+t][k];
                a[i+t][k] = temp;
            }
        }
        for(int j=i+1; j<n; j++){
            double r = a[j][i]/a[i][i];
            for(int k=i; k<m; k++)
                a[j][k] -= a[i][k] * r;
        }
    }
    if(a[n-1][m-2] == 0){
        if(a[n-1][m-1] != 0) cout << "No solution.\n";
        else cout << "Infinite solutions.\n";
        return 0;
    }
    double x[n];
    for(int i=n-1; i>=0; i--){
        x[i] = a[i][m-1];
        for(int j=i+1; j<n; j++)
            x[i] -= a[i][j] * x[j];
        x[i] /= a[i][i];
    }
    cout << "(";
    for(int i=0; i<n-1; i++)
        cout << x[i] << ", ";
    cout << x[n-1] << ").\n";
}
發佈留言

發佈留言必須填寫的電子郵件地址不會公開。