1、使用双重循环逐元素相加
最基本的方式,逐元素相加两个矩阵。
#include <stdio.h>
void addMatrices(int rows, int cols, int mat1[rows][cols], int mat2[rows][cols], int result[rows][cols]) {
for (int i = 0; i < rows; i++) {
for (int 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];
addMatrices(rows, cols, mat1, mat2, result);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
2、通过指针相加
使用指针来遍历矩阵并计算其和。
#include <stdio.h>
void addMatrices(int rows, int cols, int *mat1, int *mat2, int *result) {
for (int i = 0; i < rows * cols; i++) {
*(result + i) = *(mat1 + i) + *(mat2 + i);
}
}
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];
addMatrices(rows, cols, (int *)mat1, (int *)mat2, (int *)result);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
3、使用递归方式
通过递归计算矩阵和。
#include <stdio.h>
void addMatricesRecursive(int rows, int cols, int mat1[rows][cols], int mat2[rows][cols], int result[rows][cols], int i, int j) {
if (i == rows) {
return;
}
if (j == cols) {
addMatricesRecursive(rows, cols, mat1, mat2, result, i + 1, 0);
return;
}
result[i][j] = mat1[i][j] + mat2[i][j];
addMatricesRecursive(rows, cols, mat1, mat2, result, i, j + 1);
}
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];
addMatricesRecursive(rows, cols, mat1, mat2, result, 0, 0);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}