我在尝试按列更改行时遇到了一些问题。
我想要的只是更改静态二维数组 (3x3) 的行和列。我不想简单地打印带有反向索引的数组。我试图将数组中实际位置的值存储在int aux中,但没有任何效果。
输入:
1 2 3
4 5 6
7 8 9
输出:
1 4 7
2 5 8
3 6 9
使用这段代码,结果是相同的二维数组。我看不出问题所在,你能帮帮我吗?
#include <iostream>
using namespace std;
int main ()
{
int vec[3][3];
int x, y, aux;
//Input
for(x=0; x<3;x++)
{
for(y=0; y<3;y++)
{
cout << "POSITION ["<<x+1<<"]["<<y+1<<"]: ";
cin >> vec[x][y];
}
}
cout<<"\nPress ENTER...";
cin.ignore();
cin.get();
system("CLS");
//Array before the change
cout<<"ARRAY A"<<endl;
for(x=0; x<3;x++)
{
for(y=0; y<3;y++)
{
cout<<vec[x][y]<<"\t";
}
cout << "\n";
}
//Change
for(x=0; x<3;x++)
{
for(y=0; y<3;y++)
{
if(x!=y)
{
aux=vec[x][y];
vec[x][y]=vec[y][x];
vec[y][x]=aux;
}
}
}
//Array after the change
cout<<"\nARRAY A"<<endl;
for(x=0; x<3;x++)
{
for(y=0; y<3;y++)
{
cout<<vec[x][y]<<"\t";
}
cout << "\n";
}
cout << "\n";
system("PAUSE");
return 0;
}
最佳答案
您正在交换元素两次。因此,他们回到原来的地方。
改变
if(x!=y)
到
if(x < y)
因此仅当元素为 (2,3) 时才进行交换。如果是 (3,2),那么它已经被交换了,我们不应该再交换它。
关于c++ - C++ 行换列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20574631/