홀수 번호의 사용자 입력을 기준으로 홀수 오더의 매직 스퀘어를 출력하려고했습니다. 1 또는 3을 입력하면 올바르게 작동합니다. 내가 5, 7, 9, 11 등등과 같은 것을 입력 할 때마다 프로그램은 입력을 누르는 순간 충돌합니다. 내 코드를 검토 한 결과 문제의 위치를 정확히 알 수 없습니다. 오류 메시지가 표시되지 않습니다.특정 입력에서 프로그램이 작동을 멈 춥니 다.
작은 노트 : 마법의 사각형이 무엇인지 알고 있다면 여기에있는 알고리즘 (영어로 교수님이 C++로 변환 해주었습니다)은 모두가 같은 값을 합산하지 않기 때문에 올바른 값을 출력하지 않습니다 번호.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int n; //n = order
cout << "Enter an odd integer for the order of the Magic Square: ";
cin >> n;
cout << endl;
if(n%2 == 0) //only allows program to accept odd numbers
{
cout << "The number you have entered is not odd" << endl;
return 0;
}
int x, y; //x and y access the columns and rows of the following matrix
int magicsquare[n][n]; //creates a n by n matrix to set up magic square
int counter, square = n*n; //square is upper boundary
for(x=0; x<n; x++) //initialize all spaces in matrix with zeros
{
for(y=0; y<n; y++)
magicsquare[x][y] = 0;
}
/*Beginning of the magic square algorithm*/
x = 0, y = n/2; //initialize algorithm at the middle column of the top row
for (counter = 1; counter <= square; counter++) //magic square will contain the integers from 1 to n squared
{
magicsquare[x][y] = counter; //places current counter number at current position in the matrix or square
x--; //moves position diagonally up
y++; //and to the right
/*If a move takes you above the top row in the jth column, move to the bottom of the jth column*/
if(x<0)
x = n - 1;
/*If a move takes you outside to the right of the square in the ith row, move to the left side of the ith row*/
else if(y==n)
y = 0;
/*If a move takes you to an already filled square or if you move out of the square at the upper right
hand corner, move immediately below position of previous number*/
else if((magicsquare[x][y] != 0) || (x<0 && y==n))
{
y--; //move one space to the left back into the square
x = x+2; //move two spots down into the square and below previous number
}
}
for(x=0; x<n; x++)
{
for(y=0; y<n; y++)
cout << setw(5) << magicsquare[x][y];
cout << endl;
}
return 0;
}
나는이 이제까지 실제로 일어날 수 있는지 알고 내 머리에 논리를 따를 수는 없지만,이 코드에
큰 코드 블록을 게시하고 "충돌"한다고 말하는 것은 도움이되지 않습니다. 정확히 어떻게됩니까? 오류 메시지가 나타 납니까? 뭐? 그리고 디버거를 사용하거나 print 문을 사용하여 적어도 실패한 부분을 격리 할 수 있습니까? –
디버거에서 무슨 일이 일어나고 있는지 살펴 보았습니까? 어떤 종류의 예외가 있습니까? – adamdc78
@ MarkLuna 당신이 의도 한 것이 명확하지 않지만, 이미 제거 된 조건에 대해 테스트하기 위해 루프에서'else if'를 사용하고 있다는 사실은 논리의 어떤 것이 잘못되었다는 것을 나타냅니다. –