我正在关注de la Loubere的算法,并尝试将其编码为我的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
。
但在您进行该测试或任何测试之前,请先检查i
和j
是否在界限范围内,并根据需要进行调整。
答案 1 :(得分:0)
似乎问题是你先向上移动1步,然后向右移动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