2015-09-23 88 views
1

我遵循de la Loubere的算法,試圖將它編碼爲我的Magic Square程序的成功算法。我按照以下步驟操作:Magic Square算法問題

1)數字'1'位於頂行的中間位置。

2)然後所有的數字被放置在前一個數字的右邊一列和一列。

3)每當下一個數字放置位於頂行之上時,停留在該列中並將該數字放在底行中。

4)每當下一個數字放置位於最右邊的列之外時,停留在該行並將該數字放在最左邊的列中。

5)遇到填充正方形時,將下一個數字放在前一個數字的正下方。

6)當下一個數字位置在行和列之外時,將該數字直接放在前一個數字的下面。

但是,我沒有得到所需的數字輸出。 (也就是說,數字不在正確的位置或註冊爲零。)

任何幫助,將不勝感激(由於某些原因在上面的代碼中最後一個角括號是代碼塊外。不是問題)

編輯:我已編輯根據建議的代碼,但是我仍然發現了同樣的錯誤:

void magic(unsigned int n){//Takes in size of square (User input) 
unsigned int magicSq[15][15]; 
unsigned int sizeSquared = n * n; 
int i = 0, j = n/2; //the initial position according to de la Loubere's algorithm 
unsigned int indexer; //What we are going to use to iterate through 

//Using de la Loubere's algorithm for odd # magic squares 
for (indexer = 1; indexer <= sizeSquared; indexer++){ 
    magicSq[i][j] = indexer; 
    i--; //Decrement the row (one row up) 
    j++; //Increment the column (One column to the right) 

    //First ensure with if and else if that i and j are in bounds. 
    if (i < 0){//If row goes higher than top row 
     i += n; //i is set to bottom row 
    } 

    else if(j == n){//If number placement is outside of rightmost column 
     j -= n; //Maintain row and place # in leftmost column. 
    } 

    else{ 
     if (magicSq[i][j] != 0 || (i < 0 && j ==n)){//If the magic square has a number in it 
              //Or is outside both row and column 
      i++; //Place the number one below the previous number 
     } 
    } 

} 

}

+0

大聽到的。如果您保留原樣,可能會幫助其他人遇到相同或相似的問題。 –

回答

0
if (magicSq != 0 || (i < 0 && j ==n)){//If the magic square has a number in it 

您的代碼在這裏與您的評論不符。 magicSq將始終爲非零。你想要magicSq[i][j]!=0

但是,在您可以進行該測試或任何測試之前,請先檢查ij是否在範圍內,並根據需要進行調整。

0

什麼似乎是問題是,你先向上移動1步,然後向下移動1步,如果你擊中另一個數字。採用這種方法,實際上應該向下移動2個步驟,向左移動1個步驟,最終向下移動1步。我已經修改了邏輯位,這似乎是工作:

for (indexer = 1; indexer <= sizeSquared; indexer++){ 
    //If the magic square has a number in it, redo move and go one down 
    if (magicSq[i][j] != 0){    
     i += 2; 
     j -= 1; 
    } 
    magicSq[i][j] = indexer; 
    if (i == 0 && j == n - 1) //if in top right corner, move down 
     i++; 
    else{ 
     i--; //Decrement the row (one row up) 
     j++; //Increment the column (One column to the right) 
    } 
    if (i < 0){//If row goes higher than top row 
     i += n; //i is set to bottom row 
    } 
    else if (j == n){//If number placement is outside of rightmost column 
     j -= n; //Maintain row and place # in leftmost column. 
    } 
} 

在一個3x3正方形,我得到的結果是:

8 1 6 
3 5 7 
4 9 2