打印杨辉三角形

打印杨辉三角形

任务描述

打印出以下的杨辉三角形(要求打印出10行)

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

预期输出:

    1 
    1     1 
    1     2     1 
    1     3     3     1 
    1     4     6     4     1 
    1     5    10    10     5     1 
    1     6    15    20    15     6     1 
    1     7    21    35    35    21     7     1 
    1     8    28    56    70    56    28     8     1 
    1     9    36    84   126   126    84    36     9     1 

源代码:

#include <iostream>
#include <iomanip>
using namespace std;
#include <math.h>

const int length = 10;  // 定义杨辉三角的大小
int main()
{
    
    // 请在此添加代码
    /********** Begin *********/
	 int nums[length][length];
    int i, j;
    /*计算杨辉三角*/ 
    for(i=0; i<length; i++)
    {
        nums[i][0] = 1;
        nums[i][i] = 1;
        for(j=1; j<i; j++)
            nums[i][j] = nums[i-1][j-1] + nums[i-1][j];
    }

    /*打印输出*/ 
    for(i=0; i<length; i++)
    {
        // for(j=0; j<length-i-1; j++)
        //     printf("   ");
        for(j=0; j<=i; j++)
            printf("%5d ", nums[i][j]);
        putchar('
');
    }


    
    
    /********** End **********/
    return 0;
}
原文地址:https://www.cnblogs.com/lightice/p/12691700.html