33.cpp
上传用户:jinqiu1010
上传日期:2021-09-06
资源大小:3082k
文件大小:3k
- // 33.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <stdlib.h>
- #include <math.h>
- #include <stdio.h>
- 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) { d=p; is[k]=i; js[k]=j;}
- }
- if (d+1.0==1.0)
- { free(is); free(js); printf("err**not invn");
- 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)
- { u=k*n+j; a[u]=a[u]*a[l];}
- 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)
- { u=i*n+k; a[u]=-a[u]*a[l];}
- }
- 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("nnThe OriginalMatrix is:n");
- for(i=0;i<n;i++)
- {
- for(j=0;j<n;j++)
- {
- printf("%10.4ft", M[i*n+j]);
-
- }
- printf("n");
- }
-
- A=(double*)malloc(n*n*sizeof(double));
- for(i=0;i<n*n;i++) A[i]=M[i];
- result=inv(A,n);
- if(result!=NULL)
- {
- printf("nnThe InverseMatrix is:n");
- for(i=0;i<n;i++)
- {
- for(j=0;j<n;j++)
- {
- printf("%10.4ft", result[i*n+j]);
-
- }
- printf("n");
- }
- }
- else
- {
- printf("The Matrix is singular ! Can't be inverse!n");
- }
- free(A);
- }
- #include <conio.h>
- /* Test */
- int main(int argc, char* argv[])
- {
- printf("Hello World!n");
- double matrix[3][3]={{1,-5,-2},{-1,3,1},{3,-4,-1}};
- display(matrix[0],3);
- return 0;
- }