这个程序用来实现矩阵的乘法计算,对于不同行列之间也可计算。关键在于cM和cN的选取。源码如下:
CODE:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #define MAXM 1000 5 #define MAXN 1000 6 7 /* 定义矩阵的结构体 */ 8 typedef int ElemType; 9 typedef struct node 10 { 11 int m, n; 12 ElemType e[MAXM][MAXN]; 13 }Matrix, *PMatrix; 14 15 // 16 int Cal(PMatrix a, PMatrix b, int n, int x, int y) 17 { 18 int i; 19 int sum = 0; 20 for (i = 0; i < n; ++i) 21 { 22 sum += (a->e[x][i] * b->e[i][y]); 23 } 24 return sum; 25 } 26 27 int main() 28 { 29 while (1) 30 { 31 32 PMatrix a, b, c; 33 a = (PMatrix)malloc(sizeof(Matrix)); 34 b = (PMatrix)malloc(sizeof(Matrix)); 35 c = (PMatrix)malloc(sizeof(Matrix)); 36 memset(a->e, 0, sizeof(a->e)); 37 memset(b->e, 0, sizeof(b->e)); 38 int i, j; 39 printf("Please input a.m and a.n:\n"); 40 scanf("%d %d", &a->m, &a->n); 41 printf("Please input A:\n"); 42 for (i = 0; i < a->m; ++i) 43 for (j = 0; j < a->n; ++j) scanf("%d", &a->e[i][j]); 44 printf("Please input b.m and b.n:\n"); 45 scanf("%d %d", &b->m, &b->n); 46 printf("Please input B:\n"); 47 for (i = 0; i < b->m; ++i) 48 for (j = 0; j < b->n; ++j) scanf("%d", &b->e[i][j]); 49 50 int cM = a->m; 51 int cN = b->n; 52 printf("\nA * B :\n"); 53 for (i = 0; i < cM; ++i) 54 { 55 printf("\t"); 56 for (j = 0; j < cN; ++j) 57 { 58 c->e[i][j] = Cal(a, b, cM, i, j); 59 printf("%d ", c->e[i][j]); 60 } 61 printf("\n"); 62 } 63 } 64 return 0; 65 }