c++

c++矩阵转置怎么实现

小亿
146
2024-05-23 10:28:10
栏目: 编程语言

你可以通过以下代码实现C++矩阵的转置:

#include <iostream>

const int rows = 3;
const int cols = 3;

void transposeMatrix(int matrix[rows][cols], int result[cols][rows]) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            result[j][i] = matrix[i][j];
        }
    }
}

int main() {
    int matrix[rows][cols] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int result[cols][rows];

    transposeMatrix(matrix, result);

    std::cout << "Original Matrix:" << std::endl;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            std::cout << matrix[i][j] << " ";
        }
        std::cout << std::endl;
    }

    std::cout << "Transposed Matrix:" << std::endl;
    for (int i = 0; i < cols; i++) {
        for (int j = 0; j < rows; j++) {
            std::cout << result[i][j] << " ";
        }
        std::cout << std::endl;
    }

    return 0;
}

在上面的代码中,transposeMatrix函数用于计算矩阵的转置,并将结果存储在result数组中。在main函数中,我们定义了一个3x3的矩阵matrix,并调用transposeMatrix函数来计算转置矩阵,并输出原始矩阵和转置矩阵。

0
看了该问题的人还看了