devc++输出魔方阵
时间: 2023-12-13 21:33:42 浏览: 92
vb输出魔方阵
以下是使用Dev-C++输出魔方阵的代码:
```c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, j, k, row, col;
int **a;
printf("请输入一个奇数:");
scanf("%d", &n);
if (n <= 0 || n % 2 == 0)
{
printf("输入错误!\n");
return 0;
}
a = (int **)malloc(n * sizeof(int *));
for (i = 0; i < n; i++)
{
a[i] = (int *)malloc(n * sizeof(int));
}
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
a[i][j] = 0;
}
}
row = 0;
col = n / 2;
a[row][col] = 1;
for (k = 2; k <= n * n; k++)
{
if (a[(row - 1 + n) % n][(col + 1) % n] == 0)
{
row = (row - 1 + n) % n;
col = (col + 1) % n;
}
else
{
row = (row + 1) % n;
}
a[row][col] = k;
}
printf("魔方阵如下:\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("%5d", a[i][j]);
}
printf("\n");
}
for (i = 0; i < n; i++)
{
free(a[i]);
}
free(a);
return 0;
}
```
阅读全文