原文: https://www.programiz.com/cpp-programming/examples/matrix-transpose

该程序从用户处获取阶数为r * c的矩阵,并计算该矩阵的转置。

要理解此示例,您应该了解以下 C++ 编程主题:


在此程序中,要求用户输入行数和列数。 在此程序中,rowcolumn的值应小于 10。

然后,要求用户输入矩阵的元素。

程序将计算矩阵的转置并将其显示在屏幕上。


示例:查找矩阵的转置

  1. #include <iostream>
  2. using namespace std;
  3. int main() {
  4. int a[10][10], transpose[10][10], row, column, i, j;
  5. cout << "Enter rows and columns of matrix: ";
  6. cin >> row >> column;
  7. cout << "\nEnter elements of matrix: " << endl;
  8. // Storing matrix elements
  9. for (int i = 0; i < row; ++i) {
  10. for (int j = 0; j < column; ++j) {
  11. cout << "Enter element a" << i + 1 << j + 1 << ": ";
  12. cin >> a[i][j];
  13. }
  14. }
  15. // Printing the a matrix
  16. cout << "\nEntered Matrix: " << endl;
  17. for (int i = 0; i < row; ++i) {
  18. for (int j = 0; j < column; ++j) {
  19. cout << " " << a[i][j];
  20. if (j == column - 1)
  21. cout << endl << endl;
  22. }
  23. }
  24. // Computing transpose of the matrix
  25. for (int i = 0; i < row; ++i)
  26. for (int j = 0; j < column; ++j) {
  27. transpose[j][i] = a[i][j];
  28. }
  29. // Printing the transpose
  30. cout << "\nTranspose of Matrix: " << endl;
  31. for (int i = 0; i < column; ++i)
  32. for (int j = 0; j < row; ++j) {
  33. cout << " " << transpose[i][j];
  34. if (j == row - 1)
  35. cout << endl << endl;
  36. }
  37. return 0;
  38. }

输出

  1. Enter rows and columns of matrix: 2
  2. 3
  3. Enter elements of matrix:
  4. Enter element a11: 1
  5. Enter element a12: 2
  6. Enter element a13: 9
  7. Enter element a21: 0
  8. Enter element a22: 4
  9. Enter element a23: 7
  10. Entered Matrix:
  11. 1 2 9
  12. 0 4 7
  13. Transpose of Matrix:
  14. 1 0
  15. 2 4
  16. 9 7