矩阵的乘法运算 c 语言程序
时间: 2024-06-23 17:00:46 浏览: 11
矩阵乘法是线性代数中的基本操作,在C语言中可以通过循环和数组来实现。两个矩阵相乘的前提是第一个矩阵(称为A)的列数等于第二个矩阵(称为B)的行数。下面是简单的C语言代码示例,用于计算两个整数矩阵的乘积:
```c
#include <stdio.h>
// 定义矩阵结构体
typedef struct {
int rows;
int cols;
int data[100][100]; // 一般定义足够大的数组,这里仅作示例
} Matrix;
// 计算矩阵乘法
Matrix multiply(Matrix a, Matrix b) {
int result[100][100]; // 结果矩阵
int i, j, k;
for (i = 0; i < a.rows; i++) {
for (j = 0; j < b.cols; j++) {
result[i][j] = 0;
for (k = 0; k < a.cols; k++) { // 注意这里a.cols等于b.rows
result[i][j] += a.data[i][k] * b.data[k][j];
}
}
}
return (Matrix) {a.rows, b.cols, result};
}
// 打印矩阵
void printMatrix(Matrix m) {
int i, j;
for (i = 0; i < m.rows; i++) {
for (j = 0; j < m.cols; j++) {
printf("%d ", m.data[i][j]);
}
printf("\n");
}
}
int main() {
Matrix matrixA = {2, 2, {{1, 2}, {3, 4}}};
Matrix matrixB = {2, 2, {{5, 6}, {7, 8}}};
Matrix result = multiply(matrixA, matrixB);
printf("Matrix A:\n");
printMatrix(matrixA);
printf("Matrix B:\n");
printMatrix(matrixB);
printf("Matrix Product (A * B):\n");
printMatrix(result);
return 0;
}
```
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)