为什么我的transposeMatrix功能不起作用?

时间:2016-12-26 13:30:16

标签: function

为什么这段代码不起作用?我怎样才能改进它?我认为函数应该是void类型。 transposeMatrix()函数,它将4×5矩阵和5×4矩阵作为参数。 该函数转置4×5矩阵并将结果存储在5×4矩阵中。

void transposeMatrix(int a, int b, int N[a][b], int M[b][a])  // get 2 arrays
    {                       
        for (int i = 0; i < a; i++) {     // go through arrays
            for (int j = 0; j < b; j++)
                M[i][c] = N[i][c];
        }           
    }
    int main(void)
    {
        int a = 4, b = 5;

        int M[b][a] =  // fist array 
        {
            { 0, 10, 22, 30 },
            { 4, 50, 6, 77 },
            { 80, 9, 1000, 111 },
            { 12, 130, 14, 15 },
            { 16, 17, 102, 103 }

        };

        int N[a][b] =    // second array
        {
            { 1, 2, 3, 4, 5 },
            { 1, 2, 3, 4, 5  },
            { 1, 2, 3, 4, 5  },
            { 1, 2, 3, 4, 5  }
        };

        printf("array  M\n");
        for (int i = 0; i < a; i++) {
            for (int c = 0; c < b; i++)
                printf("%4i", M[i][c]);

            printf("\n");
            }
        transposeMatrix(a, b, N, M);  // call function

          printf("array  M after transposeMatrix function/n ");
            for (int i = 0; i < a; i++) {
                for (int c = 0; c < b; i++)

                printf("%4i", M[i][c]);

            printf("\n");
            }
        return 0;
    } 

1 个答案:

答案 0 :(得分:1)

每次我们采用转置我们都使用atranspose [i] [j] = a [j] [i]。

而在你的代码中,你正在使用M [i] [c] = N [i] [c] 这是错误的。

#include<iostream>
using namespace std;
int main()
{

int matrix[5][5],transpose_matrix[5][5];
int i,j,rows,cols;
// Taking Input In Array

  cout<<"Enter Number of ROWS :";
  cin>>rows;

  cout<<"Enter Number Of COLS  :";
  cin>>cols;
   for( i=0;i<rows;i++){
       for( j=0;j<cols;j++)
       {
           cin>>matrix[i][j];
       }
      }

      cout<<"\n Matrix You Entered\n";

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



         // Calculating Transpose of Matrix
     cout<<"\n\n\nTranspose of Entered Matrix\n";
   for( i=0;i<rows;i++){
       for( j=0;j<cols;j++)
       {
           transpose_matrix[j][i]=matrix[i][j];
       }
       cout<<endl;
      }


      //Displaying Final Resultant Array
   for( i=0;i<cols;i++){
       for( j=0;j<rows;j++)
       {
           cout<<transpose_matrix[i][j]<<"    ";
       }
       cout<<endl;
      }

返回0;     }

相关问题