用C语言写两个三维矩阵相乘
时间: 2023-08-15 08:05:49 浏览: 221
以下是使用 C 语言编写的两个三维矩阵相乘的示例代码:
```c
#include <stdio.h>
#define ROW1 2
#define COL1 3
#define ROW2 3
#define COL2 4
void matrix_mul(int mat1[][COL1], int mat2[][COL2], int res[][COL2]) {
int i, j, k;
for (i = 0; i < ROW1; i++) {
for (j = 0; j < COL2; j++) {
res[i][j] = 0;
for (k = 0; k < COL1; k++) {
res[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
}
int main() {
int mat1[ROW1][COL1] = {{1, 2, 3}, {4, 5, 6}};
int mat2[ROW2][COL2] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
int res[ROW1][COL2];
int i, j;
matrix_mul(mat1, mat2, res);
printf("Matrix 1:\n");
for (i = 0; i < ROW1; i++) {
for (j = 0; j < COL1; j++) {
printf("%d ", mat1[i][j]);
}
printf("\n");
}
printf("\nMatrix 2:\n");
for (i = 0; i < ROW2; i++) {
for (j = 0; j < COL2; j++) {
printf("%d ", mat2[i][j]);
}
printf("\n");
}
printf("\nResult:\n");
for (i = 0; i < ROW1; i++) {
for (j = 0; j < COL2; j++) {
printf("%d ", res[i][j]);
}
printf("\n");
}
return 0;
}
```
输出:
```
Matrix 1:
1 2 3
4 5 6
Matrix 2:
1 2 3 4
5 6 7 8
9 10 11 12
Result:
38 44 50 56
83 98 113 128
```
在本例中,我们定义了两个三维矩阵 `mat1` 和 `mat2`,并将它们相乘的结果储存在 `res` 中。函数 `matrix_mul()` 接受三个参数:两个矩阵和储存结果的矩阵。函数使用三个循环,分别遍历每个矩阵元素,并进行相乘。最后,我们打印了输入矩阵和结果矩阵的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)