求矩阵的逆矩阵~~~~函数·选择分支,数组~~~都用上了
#include
#include
#include
double *inv(double *a,int n)
{
int *is,*js,i,j,k,l,u,v;
double d,p;
is=(int*)malloc(n*sizeof(int));
js=(int*)malloc(n*sizeof(int));
for (k=0; k<=n-1; k++)
{ d=0.0;
for (i=k; i<=n-1; i++)
for (j=k; j<=n-1; j++)
{ l=i*n+j; p=fabs(a[l]);
if (p>d)
}
if (d+1.0==1.0)
{ free(is); free(js); printf("err**not inv\n");
return NULL;
}
if (is[k]!=k)
for (j=0; j<=n-1; j++)
{ u=k*n+j; v=is[k]*n+j;
p=a[u]; a[u]=a[v]; a[v]=p;
}
if (js[k]!=k)
for (i=0; i<=n-1; i++)
{ u=i*n+k; v=i*n+js[k];
p=a[u]; a[u]=a[v]; a[v]=p;
}
l=k*n+k;
a[l]=1.0/a[l];
for (j=0; j<=n-1; j++)
if (j!=k)
for (i=0; i<=n-1; i++)
if (i!=k)
for (j=0; j<=n-1; j++)
if (j!=k)
{ u=i*n+j;
a[u]=a[u]-a[i*n+k]*a[k*n+j];
}
for (i=0; i<=n-1; i++)
if (i!=k)
}
for (k=n-1; k>=0; k--)
{ if (js[k]!=k)
for (j=0; j<=n-1; j++)
{ u=k*n+j; v=js[k]*n+j;
p=a[u]; a[u]=a[v]; a[v]=p;
}
if (is[k]!=k)
for (i=0; i<=n-1; i++)
{ u=i*n+k; v=i*n+is[k];
p=a[u]; a[u]=a[v]; a[v]=p;
}
}
free(is); free(js);
return a;
}
void display(double M[],int n) /*显示结果*/
{
int i,j;
double *result=NULL,*A=NULL;
/*显示原矩阵*/
printf("\n\nThe OriginalMatrix is:\n");
for(i=0;i
for(j=0;j
printf("%10.4f\t", M[i*n+j]);
}
printf("\n");
}
A=(double*)malloc(n*n*sizeof(double));
for(i=0;i
if(result!=NULL)
{
printf("\n\nThe InverseMatrix is:\n");
for(i=0;i
for(j=0;j
printf("%10.4f\t", result[i*n+j]);
}
printf("\n");
}
}
else
{
printf("The Matrix is singular ! Can't be inverse!\n");
}
free(A);
}
#include
/* Test */
void main()
{
double matrix[3][3]=,,};
double matrix1[3][3]=,,};
double matrix2[4][4]=,,,};
display(matrix[0],3);
display(matrix1[0],3);
display(matrix2[0],4);
printf("push any key to be end .");
getch();
}