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

更新於: 2019 年 10 月 24 日

167 次瀏覽

開啟您的 職業生涯

完成課程獲得證書

開始
廣告