高斯消元求解线性方程组,详见高斯消元法详解
C++ 代码
/*
* @Author: lzyws739307453
* @Language: C++
*/
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 105;
const double eps = 1e-8;
double a[MAXN][MAXN];
int Select(double a[][MAXN], int n) {
int r = 1;
for (int c = 1; c <= n; c++) {
int t = r;
for (int i = r + 1; i <= n; i++)
if (fabs(a[i][c]) > fabs(a[t][c]))
t = i;
if (fabs(a[t][c]) < eps)//无解或无穷多解
continue;
if (t != r)
for (int i = c; i <= n + 1; i++)
swap(a[r][i], a[t][i]);
for (int i = n + 1; i >= c; i--)
a[r][i] /= a[r][c];
for (int i = r + 1; i <= n; i++)
if (fabs(a[i][c]) > eps)
for (int j = n + 1; j >= c; j--)
a[i][j] -= a[r][j] * a[i][c];
r++;
}
return r;
}
int Gauss(double a[][MAXN], int n) {
int r = Select(a, n);
if (r <= n) {
for (int i = r; i <= n; i++)
if (fabs(a[i][n + 1]) > eps)
return 0;//无解
return 2;//无穷多解
}
for (int i = n; i >= 1; i--)
for (int j = i + 1; j <= n; j++)
a[i][n + 1] -= a[i][j] * a[j][n + 1];
return 1;//有唯一解
}
int main() {
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n + 1; j++)
scanf("%lf", &a[i][j]);
int Judge = Gauss(a, n);
if (!Judge)
printf("No solution\n");
else if (Judge > 1)
printf("Infinite group solutions\n");
else {
for (int i = 1; i <= n; i++)
printf("%.2f\n", a[i][n + 1]);
}
return 0;
}