高斯消元解线性方程组(高斯消元,模板)

题意

给定(n imes (n + 1))的线性方程组的增广矩阵,求方程的解。

做法

枚举每一列(c)

  • 找到当前列绝对值最大的那个元素。
  • 把这一行换到最上面
  • 将该行的主元(第一个数)变成(1)(其余所有数字依次跟着变化)
  • 将下面所有行的当前列的值变成(0)(其余所有数字依次跟着变化)

代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>

using namespace std;

const int N = 110;
const double eps = 1e-8;

int n;
double a[N][N];

int gauss()
{
    int r, c; // r代表行号,c代表列号
    for(r = 0, c = 0; c < n; c ++) {
        int t = r;
        for(int i = r; i < n; i ++) { // 找到当前列中绝对值最大的元素
            if(fabs(a[i][c]) > fabs(a[t][c])) {
                t = i;
            }
        }
        if(fabs(a[t][c]) < eps) continue; // 如果这一列全0的话,直接跳过
        for(int i = c; i < n + 1; i ++) 
            swap(a[t][i], a[r][i]); // 将最大值所在的行移到最上面
        for(int i = n; i >= c; i --) a[r][i] /= a[r][c]; // 将主元变成1
        for(int i = r + 1; i < n; i ++) {
            if(fabs(a[i][c]) > eps) {
                for(int j = n; j >= c; j --) {
                    a[i][j] -= a[i][c] * a[r][j]; // 将下面所以行都减去当前行的a[i][c]倍
                }
            }
        }
        r ++;
    }
    if(r < n) {
        for(int i = r; i < n; i ++) {
            if(fabs(a[i][n]) > eps) { // 若bi不为0,则无解
                return 2;
            }
        }
        return 1;
    }
    for(int i = n - 1; i >= 0; i --) {
        for(int j = i + 1; j < n; j ++) {
            a[i][n] -= a[j][n] * a[i][j]; // 从下到上消除非主元
        }
    }
    return 0;
}

int main()
{
    scanf("%d", &n);
    for(int i = 0; i < n; i ++) {
        for(int j = 0; j < n + 1; j ++) {
            scanf("%lf", &a[i][j]);
        }
    }
    int t = gauss();
    if(!t) for(int i = 0; i < n; i ++) printf("%.2lf
", a[i][n]);
    else if(t == 1) puts("Infinite group solutions");
    else puts("No solution");
    return 0;
}
原文地址:https://www.cnblogs.com/miraclepbc/p/14406146.html