填写C ++中魔术方块的缺失条目

假设我们有一个3x3矩阵,其对角元素最初为空。我们必须填充对角线,以使行,列和对角线的总和相同。假设矩阵像-

036
505
470

填充后,将是-

636
555
474

假设对角元素为x,y,z。值将是-

  • x =(M [2,3] + M [3,2])/ 2

  • z =(M [1,2] + M [2,1])/ 2

  • y =(x + z)/ 2

示例

#include<iostream>
using namespace std;
void displayMatrix(int matrix[3][3]) {
   for (int i = 0; i < 3; i++) {
      for (int j = 0; j < 3; j++)
         cout << matrix[i][j] << " ";
         cout << endl;
   }
}
void fillDiagonal(int matrix[3][3]) {
   matrix[0][0] = (matrix[1][2] + matrix[2][1]) / 2;
   matrix[2][2] = (matrix[0][1] + matrix[1][0]) / 2;
   matrix[1][1] = (matrix[0][0] + matrix[2][2]) / 2;
   cout << "Final Matrix" << endl;
   displayMatrix(matrix);
}
int main() {
   int matrix[3][3] = {{ 0, 7, 6 },
   { 9, 0, 1 },
   { 4, 3, 0 }};
   cout << "Given Matrix" << endl;
   displayMatrix(matrix);
   fillDiagonal(matrix);
}

输出结果

Given Matrix
0 7 6
9 0 1
4 3 0
Final Matrix
2 7 6
9 5 1
4 3 8