64,670
社区成员
发帖
与我相关
我的任务
分享
while(j<3)
{
temp=a[i][j];
a[i][j]=a[j][i];
a[j][i]=temp;
}
j=j+1;
}
#include <iostream>
using namespace std;
void swap(int &a, int &b){
int temp = a;
a = b;
b = temp;
}
int main(){
int a[3][2] ={{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int nSize = 3;
cout << "before exchange" << endl;
for (int i = 0; i < nSize; ++i){
for (int j = 0; j <nSize; ++j){
cout << a[i][j] << " " ;
}
cout << endl;
}
for (int i = 0; i < nSize; ++i){
for (int j = 0; j < i; ++j){
swap(a[i][j], a[j][i]);
}
}
cout << "after exchange:" << endl;
for (int i = 0; i < nSize; ++i){
for (int j = 0; j < nSize; ++j){
cout << a[i][j] << " " ;
}
cout << endl;
}
return 0;
}
for(i=0;i<3;i++)
{
while(j<3)//这个不是死循环吗??怎么可能出结果。。。
{
temp=a[i][j];
a[i][j]=a[j][i];
a[j][i]=temp;
}
j=j+1;
}
另外,这个方法是不能交换的,例如,你访问到 a[1][2];就将它与a[2][1]交换,后来你再访问a[2][1]时,又把它与a[1][2]交换了,所以结果是不变的。
应该只交换对角线以上的元素就可以了。