求一个四乘四矩阵的逆矩阵

匿名 (未验证) 提交于 2019-12-03 00:13:02
 1 #include <stdio.h>  2 #include <stdlib.h>  3 #include <malloc.h>  4   5 int GJ(int, double **);  6 double **TwoArrayAlloc(int, int);  7 void TwoArrayFree(double **);  8   9 void main() 10 { 11     int i, j, n; 12     double **a; 13     n = 4; 14     a = TwoArrayAlloc(n, n); 15  16     a[0][0] = 5;    a[0][1] = 7;    a[0][2] = 6;    a[0][3] = 5; 17     a[1][0] = 7;    a[1][1] = 10;    a[1][2] = 8;    a[1][3] = 7; 18     a[2][0] = 6;    a[2][1] = 8;    a[2][2] = 10;    a[2][3] = 9; 19     a[3][0] = 5;    a[3][1] = 7;    a[3][2] = 9;    a[3][3] = 10; 20     if (!GJ(n, a)) 21     { 22         printf("矩阵求逆失败\n"); 23         exit(1); 24     } 25     printf("该矩阵的逆为:\n"); 26     for (i = 0; i<n; i++) 27     { 28         for (j = 0; j<n; j++) 29             printf("%.2f\t", a[i][j]); 30         printf("\n"); 31     } 32 } 33  34 int GJ(int n, double **a) 35 { 36     int i, j, k; 37     double p, q, *h; 38     h = (double *)calloc(n, sizeof(double)); 39     if (h == NULL) 40     { 41         printf("内存分配失败\n"); 42         exit(1); 43     } 44     for (k = n; k >= 1; k--) 45     { 46         p = a[0][0]; 47         if (p <= 0) 48         { 49             free(h); 50             return (0); 51         } 52         for (i = 2; i <= n; i++) 53         { 54             q = a[i - 1][0]; 55             if (i>k) 56                 h[i - 1] = q / p; 57             else 58                 h[i - 1] = -q / p; 59             for (j = 2; j <= i; j++) 60                 a[i - 2][j - 2] = a[i - 1][j - 1] + q*h[j - 1]; 61         } 62         a[n - 1][n - 1] = 1 / p; 63         for (i = 2; i <= n; i++) 64             a[n - 1][i - 2] = h[i - 1]; 65     } 66     free(h); 67     return(1); 68 } 69  70 double **TwoArrayAlloc(int r, int c) 71 { 72     double *x, **y; 73     int n; 74     x = (double *)calloc(r*c, sizeof(double)); 75     y = (double **)calloc(r, sizeof(double*)); 76     for (n = 0; n <= r - 1; ++n) 77         y[n] = &x[c*n]; 78     return (y); 79 } 80  81 void TwoArrayFree(double **x) 82 { 83     free(x[0]); 84     free(x); 85 }

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!