我遵循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
}
}
}
}
大聽到的。如果您保留原樣,可能會幫助其他人遇到相同或相似的問題。 –