【发布时间】:2020-02-23 21:12:57
【问题描述】:
所以,我正在尝试相对于主对角线交换矩阵元素。我尝试过使用 temp 方法(使用 temp 变量时切换值),也尝试过 std::swap(a,b)。不知何故,它只交换了矩阵的右上角,而另一半没有改变。
如何让所有东西交换?
我的代码:
#include <iostream>
using namespace std;
int main()
{
const int n = 7;
srand (time(NULL));
int matrix[n][n];
cout << "Original Matrix :" << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
(i == j) ? matrix[i][j] = 0 : matrix[i][j] = rand() % 100+1;
cout << matrix[i][j] << "\t";
}
cout << endl;
}
cout << "\nRemade Matrix:" << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
// swap(matrix[i][j], matrix[j][i]); //another method
cout << matrix[i][j] << "\t";
}
cout << endl;
}
return 0;
}
【问题讨论】: