其他分享
首页 > 其他分享> > 高斯消元

高斯消元

作者:互联网

高斯消元

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <iomanip>
using namespace std;
typedef long long ll;
const int N = 1e2 + 10;

const double eps = 1e-6;
int n;
double a[N][N];
void print()
{
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= n + 1; j++)
			cout << left << setw(8) << a[i][j] << " ";
		cout << endl;
	}
	cout << endl;
}
int guess()
{
	int r, c;
	for (c = 1, r = 1; c <= n; c++)
	{
		int t = r;//本轮处理r ~ n行,1 ~ r-1 行已处理,不能再变化
		for (int i = r; i <= n; i++)//找到当前列最大的数
		{
			if (fabs(a[i][c]) > fabs(a[t][c]))
				t = i;
		}
		if (fabs(a[t][c]) < eps)//如果当前列全是0,则跳过看下一列,此时只有c++, r不变,最终以r <= n来判断解的情况
			continue;
		for (int i = c; i <= n + 1; i++)//将该列最大的数所在行换到第 r 行
			swap(a[r][i], a[t][i]);
		for (int i = n + 1; i >= c; i--)//将第 r 行的第一个非零元素变为 1
			a[r][i] /= a[r][c];
		for (int i = r + 1; i <= n; i++)//将 r+1 ~ n 行的第 c 列全部变为 0
		{
			if (fabs(a[i][c]) > eps)
				for (int j = n + 1; j >= c; j--)
					a[i][j] -= a[r][j] * a[i][c];
		}
		r++;
	}
	//print();
	if (r <= n)//若系数矩阵每行都不是全 0,r应为n+1
	{
		//若r <= n, 则系数矩阵的 r ~ n 行全为 0,此时若最后一列有非 0 数,则无解
		for (int i = r; i <= n; i++)
			if (fabs(a[i][n+1]) > eps)
				return 2;
		return 1;
	}
	for (int i = n; i >= 1; i--)//若有唯一解则回带,将阶梯矩阵变为对角型矩阵
	{
		for (int j = i + 1; j <= n; j++)
			a[i][n+1] -= a[j][n+1] * a[i][j];
	}
	return 0;
}
int main()
{
	ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	cin >> n;
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= n + 1; j++)
			cin >> a[i][j];
		int t = guess();
		
	if (t == 0)
        for (int i = 1; i <= n; i++)
        {
            if (fabs(a[i][n+1]) < eps)//防止输出"-0"
                a[i][n+1] = 0;
            printf("%.2lf\n", a[i][n+1]);
        }
        	
    else if (t == 1)
    	puts("Infinite group solutions");
    else
    	puts("No solution");

	return 0;
}

标签:const,int,eps,--,include,高斯消
来源: https://www.cnblogs.com/hzy717zsy/p/16314624.html