【问题标题】:2D array transpose matrix in CC中的二维数组转置矩阵
【发布时间】:2021-07-18 13:15:07
【问题描述】:
#include <stdio.h>

void read_array( int row, int col, int a[row][col]);
void fill_arr(int row, int col,int b[row][col], int a[row][col]);
void print_arr(int row, int col, int a[row][col]);

int main(void){
    int r1,c1;
    printf("Enter number of rows>");
    scanf("%d", &r1);
    printf("Enter number of columns>");
    scanf("%d", &c1);
    int arr[r1][c1];
    read_array(r1,c1,arr);
    int arr2[c1][r1];
    fill_arr(c1,r1,arr2,arr);
    print_arr(c1,r1,arr2);
}

void read_array( int row, int col, int a[row][col]){
    int i,j;
    printf("Enter values for %d rows with each row having %d numbers> ", row, col);
    for(i=0; i<row; i++){
        for(j=0; j<col; j++){
            scanf("%d", &a[i][j]);
        }
    }
}
void fill_arr(int row, int col,int b[row][col], int a[row][col]){
    int i,j;
    for(i=0; i<row;i++){
        for(j=0; j<col; j++){
            b[i][j] = a[j][i];
        }
    }
}
void print_arr(int row, int col, int a[row][col]){
    int i,j;
    printf("Transpose: \n");
    for(i=0; i<row; i++){
        for(j=0; j<col; j++){
            printf("%d ", a[i][j]);
        }
        printf("\n");
    }
}
/*Example for a 3x4 matrix with 1-12 as input:
    Expected output:
    1 5 9
    2 6 10
    3 7 11
    4 8 12

    Actual output:
    1 4 7
    2 5 8
    3 6 9
    4 7 10
/*

我正在尝试制作一个程序来制作给定矩阵的转置矩阵。在这里,由于某种原因,列的最后一个值被重复。我怎样才能解决这个问题? (我知道stackoverflow上的转置矩阵还有其他工作代码。我需要在这个代码中找到问题)。

【问题讨论】:

  • 您是否尝试过使用调试器并单步执行您的程序?

标签: arrays c matrix multidimensional-array


【解决方案1】:

我相信您在调用fill_array() 时混淆了c1r1

此外,该函数应称为transpose_array()copy_transposed()fill 建议您填充一些固定值或零。

【讨论】:

    【解决方案2】:

    希望这是有用的。

    void fill_arr(int row, int col,int b[col][row], int a[row][col]){
          int i,j;
          for(i=0; i<row;i++){
          for(j=0; j<col; j++){
            b[j][i] = a[i][j];
          }
        }
      }
    void print_arr(int row, int col, int a[row][col]){
         int i,j;
         printf("Transpose: \n");
         for(i=0; i<row; i++){
          for(j=0; j<col; j++){
            printf("%d ", a[i][j]);
         }
          printf("\n");
    }
    }
    
    int main(void){
    int r1,c1;
    printf("Enter number of rows>");
    scanf("%d", &r1);
    printf("Enter number of columns>");
    scanf("%d", &c1);
    int arr[r1][c1];
    read_array(r1,c1,arr);
    int arr2[c1][r1];
    fill_arr(r1,c1,arr2,arr);
    print_arr(c1,r1,arr2);
    

    }

    【讨论】:

    • 仍然没有按预期工作。给出 1-12 这个奇怪的输出: 1 4 7 10 5 8 11 6 9 12 48 0
    • 在 fill_array 函数参数顺序(行、列、arr2、arr)中。这是您问题的正确代码。outpot 来自:1-12:[1 2 3 4] [5 6 7 8] [ 9 10 11 12](列顺序)
    • 没有解释的代码不是一个好的答案。
    猜你喜欢
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-20
    • 1970-01-01
    • 2012-01-22
    • 2020-01-21
    相关资源
    最近更新 更多