求矩阵的转置_动态内存分配实现
求一个3 ×3矩阵的转置,动态内存分配创建一个二维数组存储矩阵的值,然后求转置
C++代码如下:
1 #include<iostream> 2 using namespace std; 3 4 void swap(int &a, int &b) { //两个整数交换数值 5 int temp = a; 6 a = b; 7 b = temp; 8 } 9 10 int main() { 11 int(*m)[3] = new int[3][3]; 12 for (int i = 0; i < 3; i++) { //输入数组 13 for (int j = 0; j < 3; j++) { 14 cin >> m[i][j]; 15 } 16 } 17 18 for (int i = 0; i < 3; i++) //求转置 19 for (int j = 0; j < i; j++) 20 swap(m[i][j], m[j][i]); 21 22 for (int i = 0; i < 3; i++) { //打印转置后数组 23 for (int j = 0; j < 3; j++) { 24 cout<<m[i][j]<<' '; 25 } 26 cout << endl; 27 } 28 return 0; 29 }