关于魔方阵
本帖最后由 firewater 于 2015-1-3 20:43 编辑一开始写时,没有对数组进行初始化,不能正确输出结果,代码如下:
#include "stdio.h"
int main()
{
int a =;
int i, j=0, k=2,n;
printf("input a n (n=1 to 15)"); /*n为奇数*/
scanf("%d",&n);
a=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 != 0)
{
i = i + 2;
j = j - 1;
a = k;
}
else
{
a = k;
}
}
else if (1==i&&n==j)
{
i = i + 1;
a=k;
}
else if (1 == i)
{
i = n;
j = j + 1;
if (a != 0)
{
i = 2;
j = j - 1;
a = k;
}
else
{
a = k;
}
}
else if (n == j)
{
i = i - 1;
j = 1;
if (a != 0)
{
i = i + 2;
j = n;
a = k;
}
else
{
a = k;
}
}
}
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
printf("%3d",a);
}
printf("\n");
}
return 0;
}
改后的代码,对数组进行了初始化,元素的值都为0,可以输出正确结果,代码如下:
#include "stdio.h"
int main()
{
int a = {0}; /*先对元素进行初始化,全部赋值为0,则才能得到结果*/
int i, j=0, k=2,n;
printf("input a n (n=1 to 15)"); /*n为奇数*/
scanf("%d",&n);
a=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 != 0)
{
i = i + 2;
j = j - 1;
a = k;
}
else
{
a = k;
}
}
else if (1==i&&n==j)
{
i = i + 1;
a=k;
}
else if (1 == i)
{
i = n;
j = j + 1;
if (a != 0)
{
i = 2;
j = j - 1;
a = k;
}
else
{
a = k;
}
}
else if (n == j)
{
i = i - 1;
j = 1;
if (a != 0)
{
i = i + 2;
j = n;
a = k;
}
else
{
a = k;
}
}
}
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
printf("%3d",a);
}
printf("\n");
}
return 0;
}
自己顶下啊 这是教程的代码,但是我用vs2013总是运行不了,是编译器的问题,还是什么?
#include "stdio.h"
void main ()
{
int a,i,j,k,p,n;
p=1;
while (1==p)
{
printf ("enter n (n=1 to 15):");
p=0;
}
for (i=1;i<=n;i++)
{
for (j=1;j<=n;j++)
{
a=0;
}
}
j=n/2+1;
a=1;
for (k=2;k<=n*n;k++)
{
i=i-1;
j=j+1;
if ((i<1)&&(j>n))
{
i=i+2;
j=j-1;
}
else
{
if (i<1)
{
i=n;
}
if (j>n)
{
j=1;
}
}
if (a==0)
{
a=k;
}
else
{
i=i+2;
j=j-1;
a=k;
}
}
for (i=1;i<=n;i++)
{
for (j=1;j<=n;j++)
{
printf ("%5d",a);
}
printf ("\n");
}
}
页:
[1]