Программа Magic Square (C ++) - PullRequest
       34

Программа Magic Square (C ++)

6 голосов
/ 07 декабря 2010

Для тех, кто не знаком с алгоритмом классического магического квадрата: магический квадрат - это двумерный массив (nxn), который содержит числовое значение между значениями 1 и n ^ 2 в каждом местоположении.Каждое значение может появиться только один раз.Кроме того, сумма каждой строки, столбца и диагонали должна быть одинаковой.Ввод должен быть нечетным, так как я пишу решение нечетного магического квадрата.


Я выполнил задачу, но на данный момент у него есть неизвестная ошибка (логика? Вывод?), Которая меня раздражалапоследний час.Значения, которые выводятся, очень плохи.Любая помощь будет очень ценится:


#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;
  }
}

Ответы [ 5 ]

12 голосов
/ 07 декабря 2010

Вы забыли инициализировать 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 для вас.

1 голос
/ 27 февраля 2018
#include<iostream.h>
#include<iomanip.h>
int main()
{
     int arr[25][25]={0};
     cout<<"Enter size(odd):";
     int size;
     cin>>size;
     int i=0,j=(size-1)/2,n=1;
     arr[i][j]=n;
     while(n<=size*size){
           i--;
           j--;
           if(i<0&&j>=0){
                i=size-1;
                arr[i][j]=n;
                n++;
          }else if(j<0&&i>=0){
                j=size-1;
                arr[i][j]=n;
                n++;
          }else if(i<0&&j<0){
                i=i+2;
                j=j+1;
                arr[i][j]=n;
                n++;
          }else if(arr[i][j]!=0){
                i=i+2;
                j=j+1;
                arr[i][j]=n;
                n++;
          }else{  
                arr[i][j]=n;
                n++;
          }
      }
      for(i=0,i<ize;i++){  
            for(j=0,j<size;j++){
                  cout<<setw(3)<<arr[i][j];
            }
            cout<<endl;
      }
      return 0;
  }
0 голосов
/ 30 декабря 2016

Вы должны инициализировать, содержать все элементы в нули:

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

В противном случае отображается значение мусора.
N.B: функция 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;
  }
}
0 голосов
/ 07 ноября 2016

Вы должны создать динамический массив для прослушивания измерений с клавиатуры, но не забывайте удалять массивы, когда они вам не нужны

0 голосов
/ 16 июня 2013

вы не можете взять число n от пользователя, потому что вы должны определить размер массива с константой

...