求助,为什么无解,无穷解判错

P2455 [SDOI2006] 线性方程组

奇米 @ 2020-03-06 21:44:43

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

inline int read()
{
    int sum=0,ff=1; char ch=getchar();
    while(!isdigit(ch))
    {
        if(ch=='-') ff=-1;
        ch=getchar();
    }
    while(isdigit(ch))
        sum=sum*10+(ch^48),ch=getchar();
    return sum*ff;
}

int n;
db a[55][55],ans[55];

int main()
{
    scanf("%d",&n);
    for ( int i=1;i<=n;i++ ) 
        for ( int j=1;j<=n+1;j++ ) 
            scanf("%lf",&a[i][j]);
    for ( int i=1;i<=n;i++ )
    {
        int mx=i;
        for ( int j=i+1;j<=n;j++ )
            if(fabs(a[mx][i])<fabs(a[j][i])) mx=j;
        for ( int j=1;j<=n+1;j++ ) swap(a[mx][j],a[i][j]);
        for ( int j=1;j<=n;j++ )
        {
            if(i==j) continue;
            db tmp=1.0*a[j][i]/a[i][i];
            for ( int k=i+1;k<=n+1;k++ ) 
                a[j][k]-=a[i][k]*tmp;
        }
    }
    for ( int i=1;i<=n;i++ ) 
    {
        if(!a[i][i]&&!a[i][n+1]) return printf("0\n"),0;
        if(!a[i][i]&&a[i][n+1]) return printf("-1\n"),0;
        ans[i]=1.0*a[i][n+1]/a[i][i];
        if(!ans[i]) ans[i]=0;
    }
    for ( int i=1;i<=n;i++ ) printf("x%d=%.2lf\n",i,ans[i]);
    return 0;
}

|