第一种:N*N列矩阵
#include <iostream>
#define N 3
using namespace std;
void ReverseArray(int a[N][N]){
int t;
for(int i = 0; i < N; i++){
for(int j = i; j < N; j++){
if(i != j){
t=a[i][j];a[i][j]=a[j][i];a[j][i]=t;
}
}
}
}
int main() {
int a[N][N] = {{1,2,3},{4,5,6},{7,8,9}};
cout<<"原始数组:\n";
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
cout<<a[i][j]<<" ";
}
cout<<endl;
}
ReverseArray(a);
cout<<"\n转置后的数组为:\n";
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
第二种:N*M列矩阵 只改动了一点,在转置的时候补全整个矩阵
#include <iostream>
#define N 3
#define M 4
using namespace std;
void ReverseArray(int a[N][M]){
int t;
int m = M>N?M:N;
for(int i = 0; i < m; i++){
for(int j = i; j < m; j++){
if(i != j){
t=a[i][j];a[i][j]=a[j][i];a[j][i]=t;
}
}
}
}
int main() {
int max = N>M?N:M;
int a[M][M] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
cout<<"原始数组:\n";
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
cout<<a[i][j]<<" ";
}
cout<<endl;
}
ReverseArray(a);
cout<<"\n转置后的数组为:\n";
for(int i = 0; i < M; i++){
for(int j = 0; j < N; j++){
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
|