C++实现三阶矩阵相乘算法

本文提供一个使用 C++ 编写的程序,用于计算两个三阶矩阵的乘积。

代码示例

#include <iostream>
using namespace std;

const int N = 3; // 矩阵维度

// 矩阵相乘函数
void matrixMultiplication(int mat1[][N], int mat2[][N], int res[][N]) {
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            res[i][j] = 0;
            for (int k = 0; k < N; k++) {
                res[i][j] += mat1[i][k] * mat2[k][j];
            }
        }
    }
}

// 打印矩阵函数
void printMatrix(int mat[][N]) {
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            cout << mat[i][j] << ' ';
        }
        cout << endl;
    }
}

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

    // 调用矩阵相乘函数
    matrixMultiplication(mat1, mat2, res);

    cout << 'Matrix 1:' << endl;
    printMatrix(mat1);

    cout << 'Matrix 2:' << endl;
    printMatrix(mat2);

    cout << 'Result:' << endl;
    printMatrix(res);

    return 0;
}

代码解释

  1. matrixMultiplication 函数:

    • 接受三个参数:两个待相乘的矩阵 mat1mat2,以及用于存储结果的矩阵 res
    • 使用三层嵌套循环计算矩阵 res 的每个元素 res[i][j]
    • 对于每个 res[i][j],内层循环计算 mat1 的第 i 行和 mat2 的第 j 列对应元素的乘积之和。
  2. printMatrix 函数:

    • 接受一个矩阵作为参数并将其打印到控制台。
    • 使用两层嵌套循环遍历矩阵的每个元素并打印。
  3. main 函数:

    • 定义两个三阶矩阵 mat1mat2 并初始化。
    • 定义一个结果矩阵 res
    • 调用 matrixMultiplication 函数计算 mat1mat2 的乘积,并将结果存储在 res 中。
    • 调用 printMatrix 函数打印三个矩阵:mat1mat2res

总结

这段代码演示了如何使用 C++ 实现两个三阶矩阵的乘法运算。代码结构清晰,易于理解和修改。您可以根据自己的需要修改矩阵的维度和元素值,然后编译并运行程序以获得相应的结果。

C++实现三阶矩阵相乘算法(附代码示例)

原文地址: https://www.cveoy.top/t/topic/Ln3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录