#include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define endl '\n'
using namespace std;
typedef pair<int, int> PII;
typedef long long ll;
typedef long double ld;
const int N = 110;
const double eps = 1e-6;
int n;
double a[N][N];
int gauss()
{
int r, c;//行 列
for(c = 0, r = 0; 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(abs(a[t][c]) < eps)continue;
for(int j = c; j <= n; j ++)
{//与最大行交换
swap(a[t][j], a[r][j]);
}
//第一个数变为1
for(int j = n; j >= c; j --)a[r][j] /= a[r][c];
for(int i = r + 1; i < n; i ++)
{
for(int j = n; j >= c; j --)
{
a[i][j] -= a[i][c] * a[r][j];
}
}
r ++;
}
if(r < n)
{
for(int i = r; i < n; i ++)
if(abs(a[i][n]) > eps)
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; j ++)
scanf("%lf", &a[i][j]);
int t = gauss();
if(t == 0)
{
for(int i = 0; i < n; i ++)
{
if(fabs(a[i][n]) < eps)a[i][n] = 0;//防止出现-0.00
printf("%.2lf\n", a[i][n]);
}
}
else if(t == 1)printf("Infinite group solutions\n");
else printf("No solution\n");
return 0;
}
高斯消元
最新推荐文章于 2024-09-15 11:40:06 发布
本文介绍了使用高斯消元法求解线性方程组的C++代码,包括找到最大元素进行行交换、化为单位阵等步骤,最后输出解或提示无解或无限多解。
摘要由CSDN通过智能技术生成