数据结构示例之杨辉三角形

以下为输出“杨辉三角形”的简单示例:

1.用c语言实现的版本

#include<stdio.h>

int c(int x,int y);

void main() 
{
    int i,j,n=0;
    printf("Please input the value of n(n>=0):");/*控制输入正确的值以保证屏幕显示的图形正确*/
	scanf("%d",&n); 
    for(i=0; i<=n; ++i) /*控制输出N+1行*/
	{
        for(j=0; j<2*n-2*i; ++j) 
		{
            printf(" "); /*控制输出第i行前面的空格*/
		}
        for(j=0; j<i+1; ++j)
		{
            printf("%5d",c(i,j)); /*输出第i行的第j个值*/
		}
        printf("\n");
    }
}

/*求杨辉三角形中第x行第y列的值*/
int c(int x,int y) 
{
    int z;
    if ((y==0)||(y==x)) 
	{
		return 1; /*若为x行的第1或第x+1列,则输出1*/
	}
    z = c(x-1,y-1) + c(x-1,y); /*否则,其值为前一行中第y-1列与第y列值之和*/
    return z;
}

2.用C++实现的版本

#include<iostream>

int c(int x,int y);

void main() 
{
    int i,j,n=0;
    std::cout<<"Please input the value of n(n>=0):";/*控制输入正确的值以保证屏幕显示的图形正确*/
    std::cin>>n; 
    for(i=0; i<=n; ++i) /*控制输出N+1行*/
    {
        for(j=0; j<2*n-2*i; ++j) 
	{
            std::cout<<" "; /*控制输出第i行前面的空格*/
	}
        for(j=0; j<i+1; ++j)
	{
			std::cout.width(5);
            std::cout<<c(i,j); /*输出第i行的第j个值*/
	}
	std::cout<<std::endl;
    }
}

int c(int x,int y) {/*求杨辉三角形中第x行第y列的值*/
    int z;
    if ((y==0)||(y==x)) 
    {
	return 1; /*若为x行的第1或第x+1列,则输出1*/
    }
    z = c(x-1,y-1) + c(x-1,y); /*否则,其值为前一行中第y-1列与第y列值之和*/
    return z;
}

运行结果如下图所示:

《数据结构示例之杨辉三角形》

    原文作者:杨辉三角问题
    原文地址: https://blog.csdn.net/chinawangfei/article/details/52922765
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞