如何获得对称矩阵?

时间:2020-04-03 10:59:33

标签: c++ matrix

我必须编写函数:

void函数(int * a [],int sq)检查平方度方矩阵是否对称 (相对于主对角线左上-右下)并执行此矩阵的任何转置。

我的主要人

#include <iostream>
using namespace std;
void  function(int* a[], int sq);
int main() {
const int sq = 10;
int a[sq][sq];

int *tab[sq];
for (int i = 0; i < 11; i++) {
    tab[i] = a[i];
}

function(tab,sq);
return 0;
}

我的功能

void  function(int* a[], int sq) {
cout << "tell me the number and i give you (sq x sq) matrix:";
cin >> sq;

for(int i = 0; i < sq; i ++) {
    for(int j = 0 ; j < sq; j++) {
        cin >> a[i][j];
    }
}
// 3 7 8 2
// 7 4 5 5
// 8 2 1 6
// 2 5 6 1

cout << "Matrix is " << sq << " degree:" << endl;

for(int i = 0; i< sq; i++) {
    for(int j = 0; j < sq; j++) {
        if(a[0][j] == a[i][0] && a[i-1][j] == a[i][j-1] ) {
            cout << a[i][j] << " "; //  if symetrical
        }  else {
            cout << a[j][i] << " "; //if not, lets do transposition
        }
    }
    cout << endl;
    }

    } 

示例

// 3 7 8 2
// 7 4 5 5
// 8 2 1 6
// 2 5 6 1

这是对称的,应该给我输出

矩阵为4度:

3 7 8 2
7 4 5 5
8 2 1 6
2 5 6 1

但是它正在做换位并给我:

矩阵为4度:

3 7 8 2
7 4 2 5
8 5 1 6
2 5 6 1

如果我了解锻炼的内容...

1 个答案:

答案 0 :(得分:2)

替换如下所示的for循环

您的代码:

for(int i = 0; i< sq; i++) {
    for(int j = 0; j < sq; j++) {
        if(a[0][j] == a[i][0] && a[i-1][j] == a[i][j-1] ) {
            cout << a[i][j] << " "; //  if symetrical
        }  else {
            cout << a[j][i] << " "; //if not, lets do transposition
        }
    }
    cout << endl;
    }

替换为以下代码:

for(int i = 0; i< sq; i++) {
    for(int j = i; j < sq; j++) {


        if(a[i][j] == a[j][i] ) {
            cout << a[i][j] << " "; //  if symetrical
        }  else {
            cout << a[j][i] << " "; //if not, lets do transposition
        }


    }
    cout << endl;
    }