方阵的主对角线之上称为“上三角”。
请你设计一个用于填充n阶方阵的上三角区域的程序。填充的规则是:使用1,2,3….的自然数列,从左上角开始,按照顺时针方向螺旋填充。
例如:当n=3时,输出:
   1   2   3
   6   4
   5
当n=4时,输出:
   1   2   3   4
   9  10   5
   8   6
   7
当n=5时,输出:
   1   2   3   4   5
  12  13  14   6 
  11  15   7
  10   8
   9

程序运行时,从标准输入获得整数n(3~20)
程序输出:方阵的上三角部分。

要求格式:每个数据宽度为4,右对齐。


#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    int n;
    while(cin>>n)
    {
        int tri[20][20];
        int value=0,low=0,high=n;
        for(; value<n*(n+1)/2; low++,high--)
        {
            for(int i=low; i<high-low; i++)
                tri[low][i]=++value;
            for(int i=low+1; i<high-low; i++)
                tri[i][high-1-i]=++value;
            for(int i=high-low-2; i>low; i--)
                tri[i][low]=++value;
        }
        for(int i=0; i<n; i++)
        {
            for(int j=0; j<n-i; j++)
                cout<<setw(4)<<tri[i][j];
            cout<<endl;
        }
    }
    return 0;
}


posted on 2015-04-07 20:36  星斗万千  阅读(162)  评论(0编辑  收藏  举报