6

従来の魔方陣アルゴリズムに慣れていない方へ: 魔方陣は、各位置に値 1 と n^2 の間の数値を含む 2 次元配列 (nxn) です。各値は 1 回だけ表示されます。さらに、各行、列、および対角線の合計は同じでなければなりません。奇数の魔方陣の解を書いているので、入力は奇数でなければなりません。


私は問題を解決しましたが、今のところ未知のバグ (ロジック? 出力?) があり、過去 1 時間私を悩ませてきました。出力される値は非常に的外れです。どんな助けでも大歓迎です:


#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
  int n;

  cout<< "Please enter an odd integer: ";
  cin>>n;

  int MagicSquare[n][n];


  int newRow,
  newCol;

  // Set the indices for the middle of the bottom i
  int i =0 ;
  int j= n / 2;

  // Fill each element of the array using the magic array
  for ( int value = 1; value <= n*n; value++ )
  {
     MagicSquare[i][j] = value;
     // Find the next cell, wrapping around if necessary.
     newRow = (i + 1) % n;
     newCol = (j + 1) % n;
     // If the cell is empty, remember those indices for the
     // next assignment.
     if ( MagicSquare[newRow][newCol] == 0 )
     {
        i = newRow;
        j = newCol;
     }
     else
     {
        // The cell was full. Use the cell above the previous one.
        i = (i - 1 + n) % n;
     }

  }


  for(int x=0; x<n; x++)
  {
     for(int y=0; y<n; y++)
         cout << MagicSquare[x][y]<<" ";
     cout << endl;
  }
}
4

5 に答える 5

12

MagicSquareすべてゼロを含むように初期化するのを忘れました:

  for(int i = 0; i < n; i++) {
    for(int j = 0; j < n; j++) {
      MagicSquare[i][j] = 0;
    }
  }

したがって、このチェックはほとんどの場合失敗します。

if ( MagicSquare[newRow][newCol] == 0 ) {
   i = newRow;
   j = newCol;
}

C/++はそれらを0に初期化しないので。

于 2010-12-07T01:23:25.210 に答える
0

すべての要素をゼロに初期化する必要があります。

  memset(MagicSquare, 0, sizeof(MagicSquare));

それ以外の場合は、ガベージ値を表示します。
注意: memset 関数は cstring ヘッダー ファイルに含まれています。

あなたの修正されたコード:

#include<iostream>
#include<iomanip>
#include <cstring>
using namespace std;

int main()
{
  int n;

// cout<< "Please enter an odd integer: ";
  cin>>n;

  int MagicSquare[n][n];


  int newRow,
  newCol;
   memset(MagicSquare, 0, sizeof(MagicSquare));
  // Set the indices for the middle of the bottom i
  int i =0 ;
  int j= n / 2;

  // Fill each element of the array using the magic array
  for ( int value = 1; value <= n*n; value++ )
  {
     MagicSquare[i][j] = value;
     // Find the next cell, wrapping around if necessary.
     newRow = (i + 1) % n;
     newCol = (j + 1) % n;
     // If the cell is empty, remember those indices for the
     // next assignment.
     if ( MagicSquare[newRow][newCol] == 0 )
     {
        i = newRow;
        j = newCol;
     }
     else
     {
        // The cell was full. Use the cell above the previous one.
        i = (i - 1 + n) % n;
     }

  }


  for(int x=0; x<n; x++)
  {
     for(int y=0; y<n; y++)
         cout << MagicSquare[x][y]<<" ";
     cout << endl;
  }
}
于 2016-12-30T18:46:51.983 に答える
0

定数で配列のサイズを定義する必要があるため、ユーザーから数値 n を取得することはできません

于 2013-06-16T17:49:39.287 に答える