跳到正文

算法·理论

线性代数——高斯消元法

modfish_约 2 分钟
原文
文章信息与版本

文章信息

收录
2026年4月11日
更新
2026年4月11日
篇幅
约 2 分钟

版本

  1. v1当前
C++
#include <bits/stdc++.h>

using namespace std;

const int maxn = 105;
const double eps = 1e-10;

int n;
double a[maxn][maxn], xs[maxn];

void mult(int i, double k){
	for(int x = 1; x <= n + 1; x ++) a[i][x] *= k;
}
void swap(int i, int j){
	for(int x = 1; x <= n + 1; x ++) swap(a[i][x], a[j][x]);
}
void add(int i, double k, int j){
	for(int x = 1; x <= n + 1; x ++) a[j][x] += a[i][x] * k;
}
bool Gauss(){
	for(int i = 1; i <= n; i ++){
		bool fl = false;
		for(int j = i; j <= n; j ++){
			if(fabs(a[j][i]) > eps){
				fl = true, swap(i, j), mult(i, 1.0 / a[i][i]);
				break;
			}
		}
		if(!fl) return false;
		for(int j = i + 1; j <= n; j ++) add(i, -a[j][i], j);
	}
	return true;
}

int main(){
	scanf("%d", &n);
	for(int i = 1; i <= n; i ++){
		for(int j = 1; j <= n + 1; j ++){
			scanf("%lf", &a[i][j]);
		}
	}
	if(Gauss()){
		for(int i = n; i >= 1; i --) for(int j = n; j > i; j --) a[i][n + 1] -= a[j][n + 1] * a[i][j];
		for(int i = 1; i <= n; i ++) printf("%.2lf\n", a[i][n + 1]);
	}else printf("No Solution\n");
	return 0;
}
原文