杨辉三角-金字塔格式输出

来源:互联网 发布:网络封包抓取工具 编辑:程序博客网 时间:2024/05/16 01:40

输入:杨辉三角的高度height

输出:以金字塔形式打印出杨辉三角的前height行

#include <stdio.h>
#include <stdlib.h>

int main(int argc,char **argv)
{
    int height;
    printf("请输入杨辉三角的高度\n");
    scanf("%d",&height);
    int **array=(int **)malloc(sizeof(int *)*height);    //动态生成二维数组
    for(int i=0;i<height;i++)
    {
          array[i]=(int *)malloc(sizeof(int)*height);
    }

    int row,col;
    for(row=0;row<height;row++)
    {
        for(col=0;col<(height-row);col++)            //填充空格,使输出为金字塔形式
        {
            printf("  ");
        }
        for(col=0;col<=row;col++)
        {
            if(col==0||row==col)
            {
                array[row][col]=1;    
                printf("%4d",array[row][col]);     //端点值处理
            }
            else
            {
                array[row][col]=array[row-1][col]+array[row-1][col-1];//杨辉三角行列之间的特征关系
                printf("%4d",array[row][col]);
            }
                
        }
        printf("\n");
    }

    for(int i=0;i<height;i++)                //malloc与free配套使用,释放二维数组
    {
        free(array[i]);
    }
    free(array);
    return 0;
}
0 0
原创粉丝点击