Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/159.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 我构造n个奇数幻方的代码是';行不通_C++ - Fatal编程技术网

C++ 我构造n个奇数幻方的代码是';行不通

C++ 我构造n个奇数幻方的代码是';行不通,c++,C++,我正试图通过 这是我的密码 #include <iostream> #include <cstring> using namespace std; int main(){ int N; cin >> N; int magicsquares[N][N]; memset(magicsquares, 0, sizeof(magicsquares)); int i = 0, j = N/2; int num = 1;

我正试图通过

这是我的密码

#include <iostream>
#include <cstring>
using namespace std;

int main(){
    int N; cin >> N;
    int magicsquares[N][N];
    memset(magicsquares, 0, sizeof(magicsquares));

    int i = 0, j = N/2;
    int num = 1;
    while (num <= N*N){

        if (magicsquares[i][j] == 0){
            magicsquares[i][j] = num++;
            i = (i-1+N) % N;    
            j = (j+1) % N;
        } else{
            i = (i+2) % N;
            j = (j-1+N) % N;
            magicsquares[i][j] = num++;
        } 
    }

    for (int a = 0; a < N; a++){
        for (int b = 0; b < N; b++)
            cout << magicsquares[a][b] << " ";
        cout << endl;
    }
    return 0;
}
但结果是这样的:

8 1 6
3 5 7
4 9 2
0 9 0
3 0 8
7 0 2

我的代码怎么了?在
分支(未填充的方块)中,我无法计算出,如果你填充一个方块,然后设置
I
j
指向下一个要填充的方块。当您遇到一个填充的正方形(
else
分支)时,您可以反转
i
j
中的更改,并按照算法向下填充。但是在那之后,您就不会为下一步设置
i
j
,就像在
if
分支中一样。两个分支都应设置
i
j
。这应该起作用:

    if (magicsquares[i][j] == 0){
        magicsquares[i][j] = num++;
    } else{
        i = (i+2) % N;
        j = (j-1+N) % N;
        magicsquares[i][j] = num++;
    } 
    i = (i-1+N) % N;    /* Setting up i and j for next fill */
    j = (j+1) % N;      /* This should be done in both cases */

if
分支(未填充的方块)中,填充一个方块,然后设置
i
j
指向下一个要填充的方块。当您遇到一个填充的正方形(
else
分支)时,您可以反转
i
j
中的更改,并按照算法向下填充。但是在那之后,您就不会为下一步设置
i
j
,就像在
if
分支中一样。两个分支都应设置
i
j
。这应该起作用:

    if (magicsquares[i][j] == 0){
        magicsquares[i][j] = num++;
    } else{
        i = (i+2) % N;
        j = (j-1+N) % N;
        magicsquares[i][j] = num++;
    } 
    i = (i-1+N) % N;    /* Setting up i and j for next fill */
    j = (j+1) % N;      /* This should be done in both cases */