2015-02-03 5 views
-1

홀수 번호의 사용자 입력을 기준으로 홀수 오더의 매직 스퀘어를 출력하려고했습니다. 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; 
} 
나는이 이제까지 실제로 일어날 수 있는지 알고 내 머리에 논리를 따를 수는 없지만,이 코드에
+0

큰 코드 블록을 게시하고 "충돌"한다고 말하는 것은 도움이되지 않습니다. 정확히 어떻게됩니까? 오류 메시지가 나타 납니까? 뭐? 그리고 디버거를 사용하거나 print 문을 사용하여 적어도 실패한 부분을 격리 할 수 ​​있습니까? –

+0

디버거에서 무슨 일이 일어나고 있는지 살펴 보았습니까? 어떤 종류의 예외가 있습니까? – adamdc78

+0

@ MarkLuna 당신이 의도 한 것이 명확하지 않지만, 이미 제거 된 조건에 대해 테스트하기 위해 루프에서'else if'를 사용하고 있다는 사실은 논리의 어떤 것이 잘못되었다는 것을 나타냅니다. –

답변

2

: 모두 조건에 해당했을 경우

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; 

, 당신은 원 y을 수정하고 매트릭스의 끝에서 벗어나는 다음 반복을 수정하십시오.

int magicsquare[n][n];은 컴파일 타임 익스텐션이 아니며 n은 컴파일 타임 상수가 아니므로 C++ 표준에서 지원하지 않습니다. 거의 확실하게 vector을 대신 사용하고 싶습니다.

1

다음은 불법입니다 :

int magicsquare[n][n]; 

당신이 오류를 무시 않았거나 전혀 오류를 제공하지 않는 컴파일러를 사용하고 있습니까? 실수 할 때 암시하는 IDE를 사용하여 실수를 쉽게 볼 수 있습니다. 제발 끔찍한 C + +를 작성하는 메모장을 사용하지 마십시오.

고정 버전 :

int** magicsquare = new int*[n]; //creates a n by n matrix to set up magic square 
for(int i = 0; i < n+1; ++i) 
    magicsquare[i] = new int[n]; 

지금, 함께 마크 B의 힌트와 함께, 당신은이 시간에 최대 실행 얻을 것이다. delete를 사용하여 magicsquare를 정리하는 것을 잊지 마세요.

+0

사실 g ++은 이것을 확장으로 지원합니다. C99 동작이 허용되기 때문입니다.그리고 배열 확장 기술 사양의 출현과 함께 우리는이 동작을 모두 사용할 수 있습니다 : http://stackoverflow.com/a/28094952/2642059 –

+0

CodeBlocks를 사용하고 있으며 오류가 발생하지 않습니다. 그것은 전에 절대적으로 잘 작동했기 때문에 내가 무엇을했는지 몰라도 충돌이 시작되었습니다. 배열과 행렬이 C와 다르게 선언 될 것이라고 생각하지 않았습니다. C++로 이것을 시도한 것은 처음입니다. –

+0

표시 한대로 선언하면 코드에서 액세스하는 것과 같은 방식으로 매트릭스에 액세스 할 수 있습니까? ie magicsquare [행] [열] –

0

그래서 저는 마법의 사각형에 대해서는 전혀 모릅니다.

for (int counter = 1, x = 0, y = (n/2); counter <= n * n; ++counter){ 
    magicsquare[x][y] = counter; //places current counter number at current position in the matrix or square 

    if (counter % n == 0){ //moves down into the square and below previous number 
     x = (x + 1) % n; 
    } 
    else //moves position diagonally up and to the right 
    { 
     x = (x + n - 1) % n; 
     y = (y + 1) % n; 
    } 
} 

두 개의 추가 포인트 : 그러나 나는 이것이 당신이 달성하려고하는 행동이라고 생각

  1. 우리는 기술 사양 난 당신이 C99의 runtime-를 선언하지 않도록해야한다고 생각 배열 확장을 사용할 수 있습니다 때까지 코드에서 크기가 큰 배열 gcc가 허용하더라도. vector<vector<int>> magicsquare(n, vector<int>(n));
  2. 이것은 동작이 Wikipedia's article으로 표시된 것과 일치하지 않지만 시작 값과 인덱싱 순서를 조정하면 얻을 수 있습니다.
관련 문제