2017-06-21 37 views
0
# 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的魔方。輸出將是:Magic Square Code幫助,想知道它向下移動的位置在C編程

https://i.stack.imgur.com/BYTSn.png

我想知道在代碼中,將移動4倒,因爲1已經存在。同樣的事情,7下移。原則是你每次都去1和1,如果有什麼東西你會下移並繼續前進。

+0

旁白:「「請輸入偶數」' - >'「請輸入奇數」' –

+0

哦,謝謝你用來捕獲 – rprog

+1

你看了維基百科頁面[方法構建一個魔術奇數順序](https://en.wikipedia.org/wiki/Magic_square#Method_for_constructing_a_magic_square_of_odd_order)?或者[連體方法](https://en.wikipedia.org/wiki/Siamese_method)? –

回答

0

怎麼樣:

#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

+0

是的,這是一個很酷的程序。 – rprog