当前位置:首页C语言 > 正文

c语言矩阵转置函数

作者:野牛程序员:2023-11-26 11:25:04C语言阅读 2774

实现矩阵转置的C语言函数可以如下所示:

#include <stdio.h>

void transposeMatrix(int rows, int cols, 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 rows = 3;
    int cols = 4;
    int matrix[3][4] = {{1, 2, 3, 4},
                        {5, 6, 7, 8},
                        {9, 10, 11, 12}};

    int result[4][3];

    transposeMatrix(rows, cols, matrix, result);

    // 打印转置后的矩阵
    for (int i = 0; i < cols; ++i) {
        for (int j = 0; j < rows; ++j) {
            printf("%d ", result[i][j]);
        }
        printf("\\n");
    }

    return 0;
}

这个程序定义了一个矩阵转置的函数transposeMatrix,然后在main函数中调用该函数进行矩阵转置。请注意,矩阵的行数和列数需要在函数调用时传递给函数,以及定义结果矩阵的大小。在示例中,矩阵大小是3x4,转置后的矩阵大小为4x3。


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击