给定一个线性方程组,对其求解
高斯消元法
#include <cstdio>
using namespace std;
const double eps = 1e-8;
int n, mini;
double a[1000][1000];
double _abs(double x) {return x < 0 ? -x : x; }
void _swap(double &x, double &y) {double t = x; x = y; y = t; }
int main()
{
scanf("%d", &n);
for (register int i = 1; i <= n; ++i)
for (register int j = 1; j <= n + 1; ++j)
scanf("%lf", &a[i][j]);
for (register int i = 1; i <= n; ++i)
{
mini = i;
for (register int j = i + 1; j <= n; ++j)
if (_abs(a[j][i]) > _abs(a[mini][i]))
mini = j;
for (register int j = 1; j <= n + 1; ++j) _swap(a[i][j], a[mini][j]);
if (_abs(a[i][i]) <= eps)
{
puts("No Solution");
return 0;
}
for (register int j = n + 1; j >= i; --j) a[i][j] /= a[i][i];
for (register int j = 1; j <= n; ++j)
if (i ^ j)
for (register int k = n + 1; k >= i; --k)
a[j][k] -= a[i][k] * a[j][i];
}
for (register int i = 1; i <= n; ++i) printf("%.2lf\n", a[i][n + 1]);
}
原文:https://www.cnblogs.com/xuyixuan/p/9663560.html