实现如下输出:
n=10
7 8 9 10
6 1 2
5 4 3
Press any key to continue
#include<stdio.h>
#include<string.h>
int calcStart(int n)
{
int i=0;
if(n<=4) return 0;
for(i=0; i*i<=n;i++)
if(i*i==n) return (i-1)/2;
return i/2;
}
int calcNum(int n)
{
int i=0;
if(n==1) return 0;
if(n<=4) return 1;
for(i=0; i*i<=n;i++)
if(i*i==n) return i-1;
return i-1;
}
int calcRight(int in, int index)
{
return in+index-1;
}
int calcDown(int in, int index)
{
return in+index*2-2;
}
int calcLeft(int in, int index)
{
return in+index*2-2+index;
}
int calcUp(int in, int index)
{
return in+index*2-2+index+index;
}
int main(void)
{
int n;
int i,j,k,begin,in,index,nn;
int table[256][256];
printf("n=");
scanf("%d",&n);
begin=calcStart(n);
i=begin;
j=begin;
k=1;
nn=calcNum(n);
memset(table, 0x00,sizeof(table));
in=1;
index=2;
int right=calcRight(in,index);
int down=calcDown(in,index);
int left=calcLeft(in,index);
int up=calcUp(in,index);
table[i][j]=k;
for(; k<=n;)
{
k++;
if(k<=n)
{
if(k <= right) i++;
else if (k <= down) j++;
else if (k <= left) i--;
else if (k <= up) j--;
if(i+1 == begin && j+1 == begin)
{
in=k;
index+=2;
right=calcRight(in,index);
down=calcDown(in,index);
left=calcLeft(in,index);
up=calcUp(in,index);
begin--;
}
table[i][j]=k;
}
}
for(i=0;i<=nn+1;i++)
{
for(j=0;j<=nn+1;j++)
{
if(table[j][i] == 0)
{
if(n>=100) printf(" ");
else printf(" ");
}
else
{
if(n>=100) printf("%3d ",table[j][i]);
else printf("%2d ",table[j][i]);
}
}
printf("\n");
}
return 0;
}