因为你多了 3*N*N*N 次乘法以及多了3*N*N*N次加法,所以效率低下
应该用如下方法:
应该用如下方法:
程序代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { double **A; int row; int colum; }matrix; matrix* malloc_matrix(int row,int colum) { int i,j; matrix *m = (matrix *)malloc(sizeof(matrix)); m->row = row; m->colum = colum; m->A = (double **)malloc(row*sizeof(double *)); for (i=0;i<row ;i++ ) m->A[i] = (double *)malloc(colum*sizeof(double)); return m; } void free_matrix(matrix *p) { int i; for (i=0;i<p->row ;i++ ) free(p->A[i]); free(p->A); free(p); } matrix* multply(const matrix *A,const matrix *B) { int i,j,k; if (A->colum != B->row){printf("Row A and colum B must be equal!\n");exit(1);}; matrix *C = malloc_matrix(A->row,B->colum); for (i=0;i<C->row ;i++ ) for (j=0;j<C->colum ;j++ ) { C->A[i][j]=0.0; for (k=0;k<A->colum ;k++ ) C->A[i][j] = C->A[i][j] + (A->A[i][k])*(B->A[k][j]); } return C; } int main(int argc, char **argv) { matrix *A = malloc_matrix(3,4); matrix *B = malloc_matrix(4,3); matrix *C; int i, j; //check for (i =0;i<A->row;i++ ) for (j=0;j<A->colum ;j++ ) A->A[i][j] = i+1.00*j; for (i =0;i<B->row;i++ ) for (j=0;j<B->colum ;j++ ) B->A[i][j] = i+2.00*j; C = multply(A,B); for (i = 0;i<C->row ;i++ ) { for (j=0;j<C->colum ;j++ ) printf("%f\t",C->A[i][j]); printf("\n"); } free_matrix(A); free_matrix(B); free_matrix(C); }
人生就像茶几 上面放着许多杯具
人生也像厨房 里面总有一些洗具