用二维数组打印杨辉三角

#include <iostream>
#include <iomanip>
#define MAX 10
using namespace std;

int main()
{
    int array[MAX][MAX] = { 0 };

    // 给数组赋值
    for (int i = 0; i < MAX; i++)
    {
        for (int j = 0; j <= i; j++)
        {
            if (j == 0 || j == i)
            {
                array[i][j] = 1;
            }
            else
            {
                array[i][j] = array[i - 1][j - 1] + array[i - 1][j];
            }
        }
    }

    // 打印数组
    int width = 4;
    for (int i = 0; i < MAX; i++)
    {
        // 打印每行第一个
        cout << setw((MAX - i) * width) << array[i][0];
        for (int j = 1; j <= i; j++)
        {
            cout << setw(2 * width) << array[i][j];
        }
        cout << endl;
    }

    return 0;
}

image

posted @ 2022-04-15 05:26  荒年、  阅读(82)  评论(0编辑  收藏  举报