c语言 矩阵乘法

2025-06-28 03:56:55
推荐回答(1个)
回答1:

矩阵乘法程序,动态分配内存:

#include

// b[j][k] * c[k][i] = a[j][i]
void matrix(int **b,int **c, int **a, int nx, int ny, int nk)
{
int i,j,k;
for (j=0;jfor(j=0;jfor(i=0;ifor(k=0;k};
};
}

void main()
{
int i,j,k,tmp;
int b_row,b_col;
int c_row,c_col;
int a_row,a_col;
int **b,**c,**a;

// 输入B 阵 行数 列数
printf("please enter b_row b_col of matrix B\n");
scanf("%d %d",&b_row,&b_col);
c_row = b_col;

// 输入C阵 列数
printf("please enter c_col of matrix C\n");
scanf("%d",&c_col);
a_row = b_row;
a_col = c_col;

a = (int **) malloc(sizeof(int *) * a_row);
for (j=0;ja[j] = (int *) malloc(sizeof(int) * a_col);
}

b = (int **) malloc(sizeof(int *) * b_row);
for (j=0;jb[j] = (int *) malloc(sizeof(int) * b_col);
}

c = (int **) malloc(sizeof(int *) * c_row);
for (j=0;jc[j] = (int *) malloc(sizeof(int) * c_col);
}

if (!c[c_row-1]) {
printf("no enought memory\n");exit(0);
}
// 输入B阵元素
printf("Please input int matrix b[%d][%d]\n",b_row,b_col);
for (j=0;jfor (i=0;iscanf("%d",&tmp);
b[j][i] = tmp;
}
// 输入C阵元素
printf("Please input int matrix c[%d][%d]\n",c_row,c_col);
for (j=0;jfor (i=0;iscanf("%d",&tmp);
c[j][i] = tmp;
}

matrix( b ,c,a, a_col, a_row, b_col);

for(j=0;j{
for (i=0;iprintf("\n");
};
}