广元唐家河图片:C++高手在哪啊??

来源:百度文库 编辑:高校问答 时间:2024/04/28 02:58:27
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
怎么用C++输出上面的方阵???
当然不是打出一大堆的cout~~

#include <iostream>
#include <iomanip>

using namespace std;

int main(int argc, char *argv[])
{
cout << "Input the row/col number:";
int size;
cin >> size;
if( size<1 || size>10 )
size=5;
int *array = new int[size*size];
for(int i=0; i<size*size; ++i)
array[i]=0;
const int Down=0, Left=1, Up=2, Right=3;
int currentArrow=Down;
int count,x,y,tx,ty;
for(count=1,x=y=0; count<=size*size; ++count)
{
array[x*size+y] = count;
switch( currentArrow )
{
case Down: tx=x+1;ty=y; break;
case Left: tx=x; ty=y+1;break;
case Up: tx=x-1;ty=y; break;
case Right:tx=x; ty=y-1;
}
if( tx<0 || tx>size-1 || ty<0 || ty>size-1 || array[tx*size+ty] )
{
currentArrow = (currentArrow+1)%4;
switch(currentArrow)
{
case Down: ++x;break;
case Left: ++y;break;
case Up: --x;break;
case Right:--y;
}
}
else
{
x=tx;
y=ty;
}
}
for(count=0;count<size*size;++count)
{
cout << setw(3) << array[count];
if( (count+1)%size==0 )
cout<<endl;
}
delete [] array;

return 0;
}

上学期老师布置的作业,我给你贴上,觉得很不错,
你可以任意输入N(螺旋方阵的行(列)数)算法实现比较
简单,但是要慢慢理解,相信楼主你可以看懂,呵呵,有什么别的需要,
我尽力帮你,我计算机大三了,留着源程序也没有用,都给大家共享了
呵呵

#include <stdio.h> //printf()
#include <process.h> //exit()
void main() //打印螺旋方阵的另一个方法
{
int i,j,k=1,n,a[16][16];
printf("请输入一自然数N (0<N<16): ");
scanf("%d",&n);
if (n<1 || n>15)
{
printf("输入的数超界!\n");
exit(1);
}
for(i=1;i<=n/2;i++)
{
for (j=i;j<=n-i;j++)
a[i][j]=k++;
for (j=i;j<=n-i;j++)
a[j][n-i+1]=k++;
for (j=n-i+1;j>i;j--)
a[n-i+1][j]=k++;
for (j=n-i+1;j>i;j--)
a[j][i]=k++;
}
if (n%2!=0) a[(n+1)/2][(n+1)/2]=k;
for (i=1;i<=n;i++)
{
for (j=1;j<=n;j++)
printf("%5d",a[i][j]);
printf("\n");
}
}

这种题目有意思吗?

一个从外圈逐步向内圈递增的数字排列