马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 firewater 于 2015-1-3 20:43 编辑
一开始写时,没有对数组进行初始化,不能正确输出结果,代码如下:#include "stdio.h"
int main()
{
int a[16][16] =;
int i, j=0, k=2,n;
printf("input a n (n=1 to 15)"); /*n为奇数*/
scanf("%d",&n);
a[1][n/2+1]=1;
i = 1,j=n/2+1;
for (; k <= n*n; k++)
{
if (1 != i && j != n)
{
i = i - 1;
j = j + 1;
if (a[i][j] != 0)
{
i = i + 2;
j = j - 1;
a[i][j] = k;
}
else
{
a[i][j] = k;
}
}
else if (1==i&&n==j)
{
i = i + 1;
a[i][j]=k;
}
else if (1 == i)
{
i = n;
j = j + 1;
if (a[i][j] != 0)
{
i = 2;
j = j - 1;
a[i][j] = k;
}
else
{
a[i][j] = k;
}
}
else if (n == j)
{
i = i - 1;
j = 1;
if (a[i][j] != 0)
{
i = i + 2;
j = n;
a[i][j] = k;
}
else
{
a[i][j] = k;
}
}
}
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
printf("%3d",a[i][j]);
}
printf("\n");
}
return 0;
}
改后的代码,对数组进行了初始化,元素的值都为0,可以输出正确结果,代码如下:#include "stdio.h"
int main()
{
int a[16][16] = {0}; /*先对元素进行初始化,全部赋值为0,则才能得到结果*/
int i, j=0, k=2,n;
printf("input a n (n=1 to 15)"); /*n为奇数*/
scanf("%d",&n);
a[1][n/2+1]=1;
i = 1,j=n/2+1;
for (; k <= n*n; k++)
{
if (1 != i && j != n)
{
i = i - 1;
j = j + 1;
if (a[i][j] != 0)
{
i = i + 2;
j = j - 1;
a[i][j] = k;
}
else
{
a[i][j] = k;
}
}
else if (1==i&&n==j)
{
i = i + 1;
a[i][j]=k;
}
else if (1 == i)
{
i = n;
j = j + 1;
if (a[i][j] != 0)
{
i = 2;
j = j - 1;
a[i][j] = k;
}
else
{
a[i][j] = k;
}
}
else if (n == j)
{
i = i - 1;
j = 1;
if (a[i][j] != 0)
{
i = i + 2;
j = n;
a[i][j] = k;
}
else
{
a[i][j] = k;
}
}
}
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
printf("%3d",a[i][j]);
}
printf("\n");
}
return 0;
}
数组未赋值的结果
数组赋值的结果
|