C程序函数实现矩阵加法
时间: 2024-03-22 16:42:08 浏览: 21
下面是一个C程序函数实现矩阵加法的例子:
```c
#include <stdio.h>
void matrix_addition(int rows, int cols, int mat1[rows][cols], int mat2[rows][cols], int result[rows][cols])
{
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
result[i][j] = mat1[i][j] + mat2[i][j];
}
}
}
int main()
{
int rows = 2, cols = 2;
int mat1[2][2] = {{1, 2}, {3, 4}};
int mat2[2][2] = {{5, 6}, {7, 8}};
int result[2][2];
// Perform matrix addition
matrix_addition(rows, cols, mat1, mat2, result);
// Print the result
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
```
在这个例子中,我们定义了一个函数`matrix_addition`,它接受两个输入矩阵`mat1`和`mat2`,并将它们相加,结果存储在输出矩阵`result`中。在`main`函数中,我们定义了两个2x2的矩阵`mat1`和`mat2`,并将它们传递给`matrix_addition`函数。最后,我们打印输出矩阵`result`的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)