geekdoc-python-zh/docs/overiq/141.md

3.3 KiB
Raw Permalink Blame History

C 程序:打印帕斯卡三角形

原文:https://overiq.com/c-examples/c-program-to-print-pascal-triangle/

最后更新于 2020 年 9 月 24 日


什么是帕斯卡三角?

帕斯卡三角形是二项式系数的三角形阵列。看起来是这样的:

row -> 0                   1     
row -> 1                1     1     
row -> 2             1     2     1     
row -> 3          1     3     3     1     
row -> 4       1     4     6     4     1     
row -> 5    1     5     10    10    5     1

以下是计算三角形中任何给定位置的值的公式:


\ begin { pmamatrix } n \ \ k \ end { pmamatrix } = \ frac { n}{k(n-k)}

其中n代表行号,k代表列号。请注意,这些行从0开始,最左边的一列是0。因此,为了找出第 4 行第 2 列的值,我们这样做:


\ begin { pmamatrix } 4 \ \ 2 \ end { pmamatrix } = \ frac { 4}{2(4-2)} = \frac{4}{22 号!} = \frac{4*3}{2*1} = 6

下面是一个 C 程序,它根据用户输入的行数打印帕斯卡三角形:

/**************************************
 * C Program to print Pascal Triangle
***************************************/

#include<stdio.h> // include stdio.h
unsigned long int factorial(unsigned long int);

int main() 
{
    int n;

    printf("Enter number of rows: ");
    scanf("%d", &n);

    printf("\n");

    // loop for number of rows
    for(int i = 0; i <= n; i++)
    {
        // loop to print leading spaces at each line
        for(int space = 0; space < n - i; space++)
        {
            printf("   ");
        }

        // loop to print numbers in each row
        for(int j = 0; j <= i; j++)
        {
            printf("%-5d ", factorial(i) / (factorial(j) * factorial(i-j) ) );
        }

        // print newline character
        printf("\n");
    }    

    return 0;
}

unsigned long int factorial(unsigned long int n)
{
    unsigned long int f = 1;

    while(n > 0)
    {
        f = f * n;
        n--;
    }

    return f;   
}

现在试试

预期输出:

Enter number of rows: 10

                              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     
1     10    45    120   210   252   210   120   45    10    1


推荐阅读: