附带说明一下,求解矩阵用的是高斯消解法。
#include <stdio.h>
#include <math.h>
#define max_n 10
double compute(int n,double a1[max_n][max_n])
{
int i,j,k,mi;
double m,t,mx,tmp;
for(k=1;k<n;k++)
{
/*for(i=k+1,mi=k,mx=fabs(a1[k][k]);i<=n;i++)
if(fabs(a1[i][k])>mx)
{
mi = i;
mx = fabs(a1[i][k]);
}
if(k<mi)
{
for(i=k;i<=n;i++)
{ tmp = a1[k][i];
a1[k][i] = a1[mi][i];
a1[mi][i] = tmp;
}
}*/
for(i=(k+1);i<=n;i++)
{
t = a1[i][k]/a1[k][k];
for(j=k;j<=n;j++)
{
a1[i][j] = a1[i][j] - t*a1[k][j];
}
}
}
printf("\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%lf ",a1[i][j]);
if(j==n)
printf("\n");
}
}
m = 1;
for(i=1;i<=n;i++)
m *= a1[i][i];
printf("m = %lf\n",m);
return m;
}
double b_s_zhen(int i,int j,int n,double a[max_n][max_n])
{
double b[max_n][max_n];
int t,k,p=0,q=0;
for(t=1;t<=n-1;t++)
{
for(k=1;k<=n-1;k++)
{
if(t<i)
p=0;
else
p=1;
if(k<j)
q=0;
else
q=1;
b[t][k] = a[t+p][k+q];
printf("%lf ",b[t][k]);
if(k==n-1)
printf("\n");
}
}
return compute((n-1),b);
}
void main()
{
double a[max_n][max_n],a1[max_n][max_n],A[max_n][max_n],revert[max_n][max_n],D;
int i,j,n;
printf("输入矩阵维数:");
scanf("%d",&n);
printf("按行输入矩阵元素:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
scanf("%lf",&a[i][j]);
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
a1[i][j] = a[i][j];
}
D = compute(n,a1);
printf("D = %lf\n",D);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
A[i][j]=b_s_zhen(i,j,n,a);
revert[i][j]=A[i][j]/D;
}
}
printf("行列式逆阵为:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%-10lf ",revert[i][j]);
if(j==n)
printf("\n");
}
}
}