C语言 矩阵的减法 四行五列
时间: 2023-11-22 15:38:37 浏览: 31
可以使用双重循环遍历两个矩阵并逐个元素相减,将结果存储到另一个矩阵中。以下是一个示例代码:
```c
#include <stdio.h>
#define ROW 4
#define COL 5
int main() {
int matrix1[ROW][COL] = {{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20}};
int matrix2[ROW][COL] = {{5, 4, 3, 2, 1},
{10, 9, 8, 7, 6},
{15, 14, 13, 12, 11},
{20, 19, 18, 17, 16}};
int result[ROW][COL];
// 矩阵减法
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
result[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
// 打印结果
printf("矩阵1:\n");
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
printf("%d ", matrix1[i][j]);
}
printf("\n");
}
printf("\n");
printf("矩阵2:\n");
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
printf("%d ", matrix2[i][j]);
}
printf("\n");
}
printf("\n");
printf("矩阵1 - 矩阵2:\n");
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
```
输出结果为:
```
矩阵1:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
矩阵2:
5 4 3 2 1
10 9 8 7 6
15 14 13 12 11
20 19 18 17 16
矩阵1 - 矩阵2:
-4 -2 0 2 4
-4 -2 0 2 4
-4 -2 0 2 4
-4 -2 0 2 4
```
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.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)