打印数字 形状有点得味

  打印如下形状的东西:

刚开始看了半天,愣住了,然后才知道了如何做。

一:先来点简单的

  就先打印了如下:

这样的还是挺容易的,for循环打印每一行,每一行打印出特定多的,只是在for循环内部确定下一次是要增加打印的个数还是减少,代码:

#include <iostream>
using namespace std;

int main(void)
{
    const int LINES = 15;        //n*n的矩形
    int cnt = 1;        //表示某行该输出多少个数字

    for (int i = 0; i < LINES; i++)
    {
        //顺序输出数字
        for (int j = 1; j <= cnt; j++)
            cout << j;

        cout << endl;
        if (i < LINES / 2)
            cnt++;
        else
            cnt--;
    }

    system("pause");
}
easy

二:增加一点

  上面的都实现了,只要在每行开始输出特定多的空格,再在每行结尾输出逆序:

#include <iostream>
using namespace std;

int main(void)
{
    const int LINES = 15;        //n*n的矩形
    int cnt = 1;        //表示某行该输出多少个数字

    for (int i = 0; i < LINES; i++)
    {
        //输出空格
        for (int j = 0; j < LINES / 2 - cnt+1; j++)
            cout << " ";

        //顺序输出数字
        for (int j = 1; j <= cnt; j++)
            cout << j;

        //再逆序输出数字
        for (int j = cnt-1; j > 0; j--)
            cout << j;

        cout << endl;
        if (i < LINES / 2)
            cnt++;
        else
            cnt--;
    }

    system("pause");
}
easy too

三:总结

  繁事化简!

原文地址:https://www.cnblogs.com/jiayith/p/3849854.html