本帖最后由 孤不冷cing 于 2024-2-4 22:56 编辑 #include <stdio.h>
void create_magic_square(int n, char magic_square[n][n]);
void print_magic_square(int n, char magic_square[n][n]);
int main(void)
{
int n;
char magic_square[n][n];
printf("Enter size of magic square:");
scanf(" %d", &n);
printf("%5d\n", n);
print_magic_square(n, magic_square);
create_magic_square(n, magic_square);
printf("%5d\n", n);
return 0; 19 25 1 7 13
24 5 6 12 18
4 10 11 17 23
9 15 16 22 3
14 20 21 2 8
}
void create_magic_square(int n, char magic_square[n][n])
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
magic_square[i][j] = 0;
}
}
int row = 0, column = n/2;
for (int i = 1; i < (n*n+1); i++)
{
magic_square[row][column] = i;
row--, column++;
if (row < 0) row+=n;
if (column >= n) column-=n;
if (magic_square[row][column]) row++;
}
}
void print_magic_square(int n, char magic_square[n][n])
{
for (int row = 0; row < n; row++)
{
for (int column = 0; column < n; column++)
{
printf("%5d", magic_square[row][column]);
}
putchar('\n');
}
}
运行结果
[fal@ah-ipv6 c_9]$ gcc -g -o 9_5 9_5.c && ./9_5
Enter size of magic square:5
5
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
5 0 0 0 -128
34935822
原本设想结果
19 25 1 7 13
24 5 6 12 18
4 10 11 17 23
9 15 16 22 3
14 20 21 2 8
为什么会这样啊?进create函数之后,main中的n和magic_square就直接扔了吗?create结束这俩又被随机弄了个值?
但是他俩不是main的块作用域吗,这就算离开块作用域了?那我应该怎么写啊?
第二次只打印了n,没有打印magic_square。因为n太大了,一调用打印函数直接打印飞了
#include <stdio.h>
void create_magic_square(int n, char magic_square[n][n]);
void print_magic_square(int n, char magic_square[n][n]);
int main(void)
{
int n;
//char magic_square[n][n]; // 提问,这个数组有多少个字节?
// 换句话说,程序执行到这里的时候,n的值是几?
printf("Enter size of magic square:");
scanf(" %d", &n);
char magic_square[n][n];
printf("%5d\n", n);
print_magic_square(n, magic_square);
create_magic_square(n, magic_square);
printf("%5d\n", n);
return 0;
}
void create_magic_square(int n, char magic_square[n][n])
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
magic_square[i][j] = 0;
}
}
int row = 0, column = n/2;
for (int i = 1; i < (n*n+1); i++)
{
magic_square[row][column] = i;
row--, column++;
if (row < 0) row+=n;
if (column >= n) column-=n;
if (magic_square[row][column]) row++;
}
}
void print_magic_square(int n, char magic_square[n][n])
{
for (int row = 0; row < n; row++)
{
for (int column = 0; column < n; column++)
{
printf("%5d", magic_square[row][column]);
}
putchar('\n');
}
}
|