C语言编程题计算两个矩阵的乘积

C语言中,计算两个矩阵的乘积是一个常见的编程任务。可以使用直接嵌套循环法,也可以通过指针进行矩阵乘法,还可以使用递归法。每种方法都有其适用的场景和优势。

1、直接嵌套循环法

最常用的计算矩阵乘积的方法,使用三个嵌套的for循环。

#include <stdio.h>

void multiplyMatrices(int rows1, int cols1, int cols2, int mat1[rows1][cols1], int mat2[cols1][cols2], int result[rows1][cols2]) {
    for (int i = 0; i < rows1; i++) {
        for (int j = 0; j < cols2; j++) {
            result[i][j] = 0;
            for (int k = 0; k < cols1; k++) {
                result[i][j] += mat1[i][k] * mat2[k][j];
            }
        }
    }
}

int main() {
    int mat1[2][2] = {{1, 2}, {3, 4}};
    int mat2[2][2] = {{5, 6}, {7, 8}};
    int result[2][2];

    multiplyMatrices(2, 2, 2, mat1, mat2, result);

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            printf("%d ", result[i][j]);
        }
        printf("\n");
    }

    return 0;
}

2、通过指针进行矩阵乘法

使用指针来遍历矩阵元素进行乘法操作。

#include <stdio.h>

void multiplyMatrices(int rows1, int cols1, int cols2, int *mat1, int *mat2, int *result) {
    for (int i = 0; i < rows1; i++) {
        for (int j = 0; j < cols2; j++) {
            *(result + i * cols2 + j) = 0;
            for (int k = 0; k < cols1; k++) {
                *(result + i * cols2 + j) += *(mat1 + i * cols1 + k) * *(mat2 + k * cols2 + j);
            }
        }
    }
}

int main() {
    int mat1[2][2] = {{1, 2}, {3, 4}};
    int mat2[2][2] = {{5, 6}, {7, 8}};
    int result[2][2];

    multiplyMatrices(2, 2, 2, (int *)mat1, (int *)mat2, (int *)result);

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            printf("%d ", result[i][j]);
        }
        printf("\n");
    }

    return 0;
}

3、递归法

虽然递归法不是矩阵乘法的常用方法,但可以使用递归将矩阵乘法分解成较小的子问题来解决。

#include <stdio.h>

void multiplyMatricesRecursive(int rows1, int cols1, int cols2, int mat1[rows1][cols1], int mat2[cols1][cols2], int result[rows1][cols2], int i, int j, int k) {
    if (i >= rows1) return;

    if (j >= cols2) {
        multiplyMatricesRecursive(rows1, cols1, cols2, mat1, mat2, result, i + 1, 0, 0);
        return;
    }

    if (k < cols1) {
        result[i][j] += mat1[i][k] * mat2[k][j];
        multiplyMatricesRecursive(rows1, cols1, cols2, mat1, mat2, result, i, j, k + 1);
    } else {
        multiplyMatricesRecursive(rows1, cols1, cols2, mat1, mat2, result, i, j + 1, 0);
    }
}

int main() {
    int rows1 = 2, cols1 = 2, cols2 = 2;
    int mat1[2][2] = {{1, 2}, {3, 4}};
    int mat2[2][2] = {{5, 6}, {7, 8}};
    int result[2][2] = {0};

    multiplyMatricesRecursive(rows1, cols1, cols2, mat1, mat2, result, 0, 0, 0);

    for (int i = 0; i < rows1; i++) {
        for (int j = 0; j < cols2; j++) {
            printf("%d ", result[i][j]);
        }
        printf("\n");
    }

    return 0;
}

推荐阅读
cjavapy编程之路首页