C++ 程序:转置矩阵

编写一个 C++ 程序来转置矩阵,并附带一个示例。在嵌套的 for 循环中,我们将原始矩阵的行列值赋给转置矩阵的列行位置。接下来,我们使用另一个嵌套的 for 循环来打印转置矩阵的输出。

#include<iostream>
using namespace std;

int main()
{
	int i, j, rows, columns;
	
	cout << "\nPlease Enter the rows and Columns =  ";
	cin >> i >> j;
	
	int orgMat[i][j], transMat[i][j];
	
	cout << "\nPlease Enter the Original Items\n";
	for(rows = 0; rows < i; rows++)	{
		for(columns = 0; columns < i; columns++) {
			cin >> orgMat[rows][columns];
		}	
	}	
	for(rows = 0; rows < i; rows++)	{
		for(columns = 0; columns < j; columns++) {
			transMat[columns][rows] = orgMat[rows][columns];
		}
	}
	cout << "\nThe Final Result after Transposing \n";
	for(rows = 0; rows < i; rows++)	{
		for(columns = 0; columns < j; columns++) {
			cout << transMat[rows][columns] << "  ";
		}
		cout<<"\n";
	}
 	return 0;
}
Please Enter the rows and Columns =  3 3

Please Enter the Original Items
10 20 30
40 50 60
70 80 90

The Final Result after Transposing
10  40  70  
20  50  80  
30  60  90 

转置矩阵示例程序

在此 C++ 示例中,我们使用了额外的 cout 语句来向您展示行、列值以及原始元素值。并在每次迭代中展示转置矩阵的元素值。

#include<iostream>
using namespace std;

int main()
{
	int i, j, rows, columns;
	
	cout << "\nPlease Enter the rows and Columns of Matrix to Transpose =  ";
	cin >> i >> j;
	
	int orgMat[i][j], transMat[i][j];
	
	cout << "\nPlease Enter the Original Matrix Items\n";
	for(rows = 0; rows < i; rows++)	{
		for(columns = 0; columns < i; columns++) {
			cin >> orgMat[rows][columns];
		}	
	}	
	for(rows = 0; rows < i; rows++)	{
		cout << "\n---The Result of " << rows + 1 << " Row Iteration---";
		for(columns = 0; columns < j; columns++) {
			transMat[columns][rows] = orgMat[rows][columns];
			
			cout << "\n---The Result of " << rows + 1 << " Row and "<< columns + 1 << " Column Iteration---";
			cout << "\nValue of transMat[columns][rows] = "<< transMat[columns][rows] << " and orgMat[rows][columns] =  " << orgMat[rows][columns];
		}
	}
	cout << "\nThe Final Result after Transposing Matrix \n";
	for(rows = 0; rows < i; rows++)	{
		for(columns = 0; columns < j; columns++) {
			cout << transMat[rows][columns] << "  ";
		}
		cout<<"\n";
	}
 	return 0;
}
Program to Transpose a Matrix using for loop Example