80pts求助

P2455 [SDOI2006] 线性方程组

Huhu12346 @ 2023-04-10 13:40:27

高斯约旦消元,80pts求助

#include <bits/stdc++.h>
using namespace std;

const int N = 505;
const double eps = 1e-6;

int n;
double a[N][N], ans[N];
int Gauss()
{
    for (int i = 1; i <= n; i++)
    {
        int M = i;
        for (int j = i + 1; j <= n; j++)
        {
            if (abs(a[M][i]) < abs(a[j][i]))
                M = j;
        }
        if (i != M)
            swap(a[i], a[M]);

        if (abs(a[i][i]) < eps)
            return 0;

        double div = a[i][i];
        for (int j = i; j <= n + 1; j++)
            a[i][j] /= div;
        for (int j = i + 1; j <= n; j++)
        {
            div = a[j][i];
            for (int k = i; k <= n + 1; k++)
                a[j][k] -= a[i][k] * div;
        }
    }
    ans[n] = a[n][n + 1];
    for (int i = n - 1; i >= 1; i--)
    {
        ans[i] = a[i][n + 1];
        for (int j = i + 1; j <= n; j++)
            ans[i] -= a[i][j] * ans[j];
    }
    return 1;
}

int main()
{
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n + 1; j++)
        {
            cin >> a[i][j];
        }   
    } 

    int check = Gauss();

    for(int i=1;i<=n;i++)
    {
        if(fabs(ans[i]) < 1e-8) 
        {
            ans[i] = 0.0;
        }
    }     
    if (check == 1)
    {
        for (int i = 1; i <= n; i++)
        {
            cout << "x" << i << "=";
            printf("%.2lf\n", ans[i]);
        }   
    }
    else
    {
        printf("0\n");
    }
    return 0;
}

by Special_Tony @ 2024-03-12 13:58:21

@Huhu12346 你的-1呢


|