C 程序求矩阵的转置


2022年2月22日, Learn eTutorial
1608

什么是矩阵的转置?

在这个 C 程序中,我们需要计算矩阵的转置。因此我们需要接受一个矩阵并计算其转置。所以首先我们需要知道矩阵的转置是什么意思。矩阵的转置意味着我们要将矩阵的列转换为行,反之亦然。

示例:如果矩阵是

2 5

6 7

那么矩阵的转置是

2    6

5    7


此程序的逻辑是首先将变量 m,n, ma[][] 声明为整数。然后将矩阵的阶数读入变量 m,n。使用嵌套的 for 循环从用户读取矩阵并将其保存到数组 ma[i][j] 中。然后显示给定的矩阵。为了找出矩阵的转置,将每个元素的列更改为行,行更改为列。所以我们使用一个带条件 j 的嵌套 for 循环

算法

步骤 1:包含头文件以在 C 程序中使用内置头文件。

步骤 2:将变量 i,j,m,n,ma[10][10] 声明为整数。

步骤 3:将矩阵的阶数从用户读入变量 mn

步骤 4:使用 for 循环将矩阵的系数读入矩阵 ma[i[j]

步骤 5:使用 for 循环显示给定的矩阵的每个元素 ma[i]j]

步骤 6:使用带条件 j 的 for 循环

步骤 7:使用另一个带条件 i 的 for 循环

步骤 8:将 ma[i][j] 显示为转置矩阵

 

C 语言源代码

                                          #include <stdio.h>

void main() {
  static int ma[10][10];
  int i, j, m, n;
  printf("Enter the order of the matrix \n"); /* enter the order of matrix */
  scanf("%d %d", & m, & n); /* accepting the values */
  printf("Enter the coefficients of the matrix\n");
  for (i = 0; i < m; ++i) {
    for (j = 0; j < n; ++j) {
      scanf("%d", & ma[i][j]);
    }
  }
  printf("The given matrix is \n"); /* just prints the matrix as such */
  for (i = 0; i < m; ++i) {
    for (j = 0; j < n; ++j) {
      printf(" %d", ma[i][j]);
    }
    printf("\n");
  }
  printf("The transpose of the matrix \n"); /* finding the transpose of matrix using loop */
  for (j = 0; j < n; ++j) {
    for (i = 0; i < m; ++i) {
      printf(" %d", ma[i][j]);
    }
    printf("\n");
  }
} /* End of main() */
                                      

输出

Enter the order of the matrix
2*2

Enter the coefficients of the matrix
 3 -1
 6  0

The given matrix is
 3 -1
 6  0

The transpose of the matrix is
 3 6
-1 0