高斯消元其实很好理解,就是我们平常解线性方程组用的消元法,不过在代码中实现需要用到矩阵,这里就只放代码,思路网上的大佬们已经讲的很清楚了
Code
#include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<iostream> #include<iomanip> #include<algorithm> using namespace std; #define eps 1e-8 #define rg register const int N=1e3+1; int n; double m[N][N]; inline double Fabs(double x) {return x>0?x:-x;} void ready() { scanf("%d",&n); for(rg int i=1;i<=n;i++) for(rg int j=1;j<=n+1;j++) scanf("%lf",&m[i][j]); } void work() { for(rg int i=1;i<=n;i++){ int maxx=i; for(rg int j=i;j<=n;j++) if(Fabs(m[j][i]-m[maxx][i])<=eps) maxx=j; for(rg int j=1;j<=n+1;j++){ double t=m[i][j]; m[i][j]=m[maxx][j]; m[maxx][j]=t;} if(Fabs(m[i][i])<=eps){ printf("No Solution\n"); return;} for(rg int j=i+1;j<=n+1;j++) m[i][j]/=m[i][i]; for(rg int j=1;j<=n;j++) if(i!=j) for(rg int k=i+1;k<=n+1;k++) m[j][k]-=m[j][i]*m[i][k]; } for(rg int i=1;i<=n;i++) printf("%.2lf\n",m[i][n+1]); } int main() { ready(); work(); return 0; }