#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#pragma warning(disable:4996)
void swap(double **row,double *b,int r,int t)//将矩阵A和向量b的第r行和第t行交换
{ double *m,n;
m=row[r];row[r]=row[t];row[t]=m;
n=b[r];b[r]=b[t];b[t]=n;
return;
}
void gauss(double **row,int n,double *b)//高斯消元
{ int i,j,flag,k;
for(j=0;j<n;j++)
{ flag=0;
for(i=j;i<n;i++)
{ if(row[i][j]>0) flag=1;
if(flag==1&&row[j][j]==0&&i!=j) swap(row,b,j,i);//如果第j行第j列为0,通过交换使其不为0
if(flag==1&&row[i][j]!=0&&i!=j)
{ for(k=j+1;k<n;k++)//消去i,j元素
row[i][k]=row[i][k]-row[i][j]/row[j][j]*row[j][k];
b[i]=b[i]-row[i][j]/row[j][j]*b[j];
row[i][j]=0;
}
}
}
return;
}
int main()
{ double **row,*b,*x;
int i,j,n;
printf("请输入矩阵阶数:");
scanf("%d",&n);
row=(double**)malloc(sizeof(double*)*n);
for(i=0;i<n;i++)
row[i]=(double*)malloc(sizeof(double)*n);
b=(double*)malloc(sizeof(double)*n);
x=(double*)malloc(sizeof(double)*n);
printf("请输入矩阵A:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%lf",&row[i][j]);
printf("请输入向量b:\n");
for(i=0;i<n;i++)
scanf("%lf",&b[i]);
gauss(row,n,b);
if(fabs(row[n-1][n-1])<1e-8) printf("No Solution or Infinite solutions!\n");
else
{ for(i=n-1;i>=0;i--)
{ for(j=n-1;j>i;j--)
b[i]=b[i]-row[i][j]*x[j];
x[i]=b[i]/row[i][i];
}
for(i=0;i<n;i++)
printf("x%d=%.3lf\n",i+1,x[i]);
}
free(b);free(x);
for(i=n-1;i>=0;i--)
free(row[i]);
free(row);
return 0;
}
|