打印螺旋方阵
从csdn看到这个,觉得挺有意思:c/c++ 打印下面的图形,看谁代码最短,只准用标准库
12345678
282930313233349
2748495051523510
2647606162533611
2546596463543712
2445585756553813
2344434241403914
2221201918171615 可以试着找一个公式。两条对角线将正方形分成四份,首先判断落在哪一份,而对于每个部分,数据分布还是挺规律的,找出公式就可以了。然后再看看这个公式还有没有什么特殊之处可以用来简化程序的 模拟填充就可以了
先初始化到0
然后模拟人填充过程 最简单的代码是递归代码
每次只填充一层
我觉得 最简单的代码就是直接一个printf,呵呵:lol :)
我想最好是一重循环做到
最低要求是两重循环
最多50行
不含空行和{, }行 #include <stdio.h>
#include <stdlib.h>
#define Max 16
int main(void)
{
int square = {0};
int n, num, len, x, y, xp, yp, inc;
int i, j, k;
printf("Input n value(n <= 1 exit):");
scanf("%d", &n);
printf("\n");
if (n <= 1) exit(1);
if (n > Max) n = Max;
len = n - 1;num = 1;
for (i = 0; i < n / 2; i ++)
{
x = i; y = i;
for (j = 1; j <= 4; j ++)
{
if (j <= 2) inc = 1; else inc = -1;
if (j & 1) {xp = 0; yp = inc;} else {xp = inc; yp = 0;}
for (k = 1; k <= len; k ++)
{
square = (num ++);
x += xp; y += yp;
}
}
len -= 2;
}
if (n & 1) square = n * n;
for (i = 0; i < n; i ++)
{
for (j = 0; j < n; j ++)
printf("%4d", square);
printf("\n");
}
return (0);
}在8时候的输出 1 2 3 4 5 6 7 8
28293031323334 9
2748495051523510
2647606162533611
2546596463543712
2445585756553813
2344434241403914
2221201918171615 更简化的双重循环
#include <stdio.h>
#include <stdlib.h>
#define Max 16
int main(void)
{
int square = {0};
int n, num, len, x, y;
int i, j;
printf("Input n value(n <= 1 exit):");
scanf("%d", &n);
printf("\n");
if (n <= 1) exit(1);
if (n > Max) n = Max;
len = n - 1;
num = 1;
for (i = 0; i < n / 2; i ++)
{
x = i; y = i;
for (j = 0; j < len; j ++)
{
square = num + j;
square = num + len + j;
square = num + (len << 1) + j;
square = num + (len << 1) + len + j;
}
num += (len << 2);
len -= 2;
}
if (n & 1) square = n * n;
for (i = 0; i < n; i ++)
{
for (j = 0; j < n; j ++)
printf("%4d", square);
printf("\n");
}
return (0);
} //另一种思路
#include <stdio.h>
#include <stdlib.h>
#define Max 16
int main(void)
{
int square = {0};
int n, num;
int i,x, y, xInc,yInc;
printf("Input n value(n <= 1 exit):");
scanf("%d", &n);
printf("\n");
if (n <= 1) exit(1);
if (n > Max) n = Max;
for (i=1;i<=n;i++)
{
square=-1; //在四边建立围墙
square=-1;
square=-1;
square=-1;
}
x=y=num=xInc=1;
yInc=0;
while (true)
{
square=num;
if (num==n*n)
break;
if ( square!=0) //撞到墙了,或者已填充
{
switch(xInc*2+yInc+2)
{
case 4: xInc=0; yInc=1; break; //改变方向
case 3: xInc=-1; yInc=0; break;
case 0: xInc=0;yInc=-1; break;
case 1: xInc=1;yInc=0; break;
}
}
x+=xInc;
y+=yInc;
num++;
}
for (y = 1; y <= n; y ++)
{
for (x = 1; x <= n; x++)
printf("%4d", square[ y ][ x ]);
printf("\n");
}
return (0);
} 我也抛个砖,不过好像打反了,实在懒得改了,不知有没有哪位能突破直接打印!
#include <iostream>
#include <math.h>
using namespace std;
inti,j,t,p,q,z,data;
void test2()
{
#define r(x) (int)(x>0?x+.5:x-.5)
#define O(x,n,k) r(1.4*n*x(0.78*k/n))
#define g(n,k,x) (abs(x)<n?x:n*x/abs(x))+3
for(i=1;i<64;i++) { p=sqrt(i);t=p%2?(p+1)/2:p/2;z=i-4*t*t+3*t;
data=i;}
for(i=0;i<8;i++){for(int j=0;j<8;j++) cout<<"\t"<<64-data;cout<<endl;}
}