gpt4 book ai didi

c - Magic Square代码帮助,想知道将数字向下移动到哪里用C编程

转载 作者:行者123 更新时间:2023-11-30 16:44:09 28 4
gpt4 key购买 nike

# include <stdio.h>
# include <stdlib.h>
int main(void)
{
int s;
int row;
int column;
int k;
int array[99][99] ;

printf("Enter the dimension of the square : ") ;
scanf("%d", &s) ;

if (s % 2 == 0)
{
printf("Please enter an even number") ;
goto last;
}


column = (s + 1) / 2 ;
row = 1 ;

int sqr1 = s*s;

for(k = 1 ; k <= sqr1 ; k++)
{
array[row][column] = k ;
if(k % s == 0)
{
row = (row + 1);
goto loop ;
}
if(row == 1)
row = s ;
else
row = row - 1 ;
if(column == s)
column = 1;
else
column = column + 1 ;
loop : ;
}
for (row = 1 ; row <= s ; row++)
{
for (column = 1 ; column <= s ; column++)
{
printf("%d\t", array[row][column]) ;
}
printf("\n\n") ;
}
last : ;
return 0;
}

我想知道是否有人可以告诉我代码在哪里记录了数字。假设我想要一个 3x3 幻方。输出将是:

/image/BYTSn.png

我想知道代码中的哪个位置会将 4 向下移动,因为 1 已经在那里了。 7 向下移动也是如此。原则是每次向上 1 次、向右 1 次,如果那里有东西,您向下移动并继续前进。

最佳答案

关于:

#include <stdio.h>
#include <string.h>

#define N (3)

int main( int argc, char * argv[] )
{
int square[ N ][ N ];

int i = N / 2;
int j = N - 1;
int num = 1;

memset( square, 0, sizeof(square) );

while( num <= N * N )
{
if( (i == -1) && (j == N) )
{
i = 0;
j = N - 2;
}
else
{
if( i < 0 )
i = N - 1;

if( j == N )
j = 0;
}

if( square[i][j] )
{
i++;
j = j - 2;

continue;
}
else
{
square[i][j] = num;
num++;
}

j++;
i--;
}

printf("N = %d\n", N );
printf("Sum = %d\n\n", N * (N * N + 1) / 2 );

for( i = 0; i < N; i++ )
{
for( j = 0; j < N; j++ )
printf("%3d ", square[i][j]);

printf("\n");
}

return 0;
}

输出:

N   = 3
Sum = 15

2 7 6
9 5 1
4 3 8

N = 5
Sum = 65

9 3 22 16 15
2 21 20 14 8
25 19 13 7 1
18 12 6 5 24
11 10 4 23 17

N = 7
Sum = 175

20 12 4 45 37 29 28
11 3 44 36 35 27 19
2 43 42 34 26 18 10
49 41 33 25 17 9 1
40 32 24 16 8 7 48
31 23 15 14 6 47 39
22 21 13 5 46 38 30

N = 9
Sum = 369

35 25 15 5 76 66 56 46 45
24 14 4 75 65 55 54 44 34
13 3 74 64 63 53 43 33 23
2 73 72 62 52 42 32 22 12
81 71 61 51 41 31 21 11 1
70 60 50 40 30 20 10 9 80
59 49 39 29 19 18 8 79 69
48 38 28 27 17 7 78 68 58
37 36 26 16 6 77 67 57 47

引用文献:

  1. https://en.wikipedia.org/wiki/Siamese_method

  2. https://en.wikipedia.org/wiki/Magic_square

关于c - Magic Square代码帮助,想知道将数字向下移动到哪里用C编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44682722/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com