再记录一下,看算法容易,自己写这个时还是出了点问题。
/*author: livahu
**2006.11.24
*/

#include <stdio.h>

#define MAX_SIZE 15

int main(void)
{
static int square[MAX_SIZE][MAX_SIZE];
int i, j, row, column;
int count;
int size;

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

if (size < 1 || size > MAX_SIZE + 1) {
printf("Error! ");
return -1;
}

if (!(size % 2)) {
printf("Error! ");
return -1;
}

for (i = 0; i < size; i++)
for (j = 0; j < size; j++)
square[i][j] = 0;

square[0][(size - 1) / 2] = 1;

i = 0;
j = (size - 1) / 2;
for (count = 2; count <= size * size; count++) {
row = (i - 1 < 0) ? (size - 1) : (i - 1);
column = (j - 1 < 0) ? (size - 1) : (j - 1);
if (square[row][column])
i = (++i) % size;
else {
i = row;
j = (j - 1 < 0) ? (size - 1) : --j;
}
square[i][j] = count;
}

for (i = 0; i < size; i++) {
for (j = 0; j < size; j++)
printf("%5d", square[i][j]);
printf(" ");
}
printf(" ");

}
/*author: livahu
**2006.11.24
*/
#include <stdio.h>
#define MAX_SIZE 15
int main(void)
{
static int square[MAX_SIZE][MAX_SIZE];
int i, j, row, column;
int count;
int size;
printf("Enter the size of the square: ");
scanf("%d", &size);
if (size < 1 || size > MAX_SIZE + 1) {
printf("Error! ");
return -1;
}
if (!(size % 2)) {
printf("Error! ");
return -1;
}
for (i = 0; i < size; i++)
for (j = 0; j < size; j++)
square[i][j] = 0;
square[0][(size - 1) / 2] = 1;
i = 0;
j = (size - 1) / 2;
for (count = 2; count <= size * size; count++) {
row = (i - 1 < 0) ? (size - 1) : (i - 1);
column = (j - 1 < 0) ? (size - 1) : (j - 1);
if (square[row][column])
i = (++i) % size;
else {
i = row;
j = (j - 1 < 0) ? (size - 1) : --j;
}
square[i][j] = count;
} 
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++)
printf("%5d", square[i][j]);
printf(" ");
}
printf(" ");
}
本文介绍了一个使用C语言实现的魔术方阵生成算法,该算法能够生成奇数大小的正方形矩阵,其中每个单元格包含从1到n²的唯一整数,并确保每行、每列及两条对角线上的数字之和相等。

2498

被折叠的 条评论
为什么被折叠?



