魔術方陣 — C

Sharon Peng
3 min readAug 7, 2019

--

我的步驟大概如下:

  1. 輸入( while(scarf(“%d”, &N) != EOF) )
  2. 二維陣列的初始化
  3. column(行), row(列),還有放入數字的替代變數(key)。
  4. 當出現偶數時,要印出的文字。
  5. 進入正題,將每個數字放到相對應的位子。(比較複雜一點)
  6. 印出題目所要的條件。

我這邊就主要提說如何將每個數字放到相對應的位子。

有四種情況需要考慮:

1. 當 c 超出範圍

2. 當 r 超出範圍

3. 當 c, r超出範圍

4. 要放入的那格,已經擺好數字

完整的程式碼:

#include<stdio.h>int main()
{
int N, flag = 0;
while(scanf("%d", &N) != EOF)
{
int Square[ N ][ N ];
int x, y;
//陣列初始化
for ( x = 0; x < N; x++ )
for ( y = 0; y < N; y++ )
Square[x][y] = 0;
//col, row初始化
int col = N-1;
int row = N / 2;
int key = 1;

int i, j;
Square[col][row] = key; //偶數的狀況
if(N % 2 == 0)
{
if(flag != 0)
printf("\n");
printf("It is not an odd number.\n");
}
else
{
while(key <= N * N)
{
row++;
col++;
if(row == N && col == N)
{
row = row - 1;
col = col - 2;
}
else if (row == N)
{
row = row - N;
}
else if(col == N)
{
col = col - N;
}
else
{
if(Square[col][row] != 0)
{
row = row - 1;
col = col - 2;
}
}
key++;
Square[col][row] = key;

}

//印出總和,題目條件
int sum = 0;
for(i = 0; i < N; ++i)
{
sum = sum + Square[0][i];
}
if(flag != 0){
printf("\n");
}
printf("%d\n", sum);
for(i = 0; i < N; ++i)
{
for(j = 0; j < N; ++j)
{
printf("%5d", Square[i][j]);
flag = 1;
}
printf("\n");
}
}
}
return 0;
}

--

--

Sharon Peng
Sharon Peng

No responses yet