程序基本算法习题解析 编写代码实现杨辉三角

先附上书上的代码(书上用c写的,这里转换成了c++,但是思路没变):

#include "stdafx.h"
#include<iostream>
using namespace std;
int main()
{
    int a[11][20],i,j;
    for(i=0;i<11;i++)
        for(j=0;j<20;j++)
            a[i][j] = 0;
    for(i=0;i<10;i++)
    {
        for(j=0;j<=i;j++)
        {
            if(j<1)
            a[i][j] = 1;
            else if(i==0)
                break;
            else
                a[i][j] = a[i-1][j-1]+a[i-1][j];
        }
    }
    for(i=0;i<10;i++)
    {
        for(j=0;j<=i;j++)
        cout << a[i][j];
        cout << endl;
    }
    system("pause");
    return 0;
}

运行结果如下:

但是我认为书上这个程序写得不完善,首先,不能自定义行数,其次,输出值之间没有间隔且不是以美观的三角形式进行输出。

针对以上问题,我对程序做了改进,如下:

// Chapter1_7.cpp : Defines the entry point for the application.
// 编写代码实现杨辉三角

#include "stdafx.h"
#include<iostream>
using namespace std;

int main()
{
	int layer,row,colume;
	cout << "input the number of layers: " ;
	cin >> layer;
	row = layer;
	colume = 2*layer-1;
	//申请空间
	int **a = new int *[row];
	int i,j;
	for(i=0;i<row;i++)
	{
		a[i] = new int[colume];
	}
	//赋初值
	for(i=0;i<row;i++)
		for(j=0;j<colume;j++)
			a[i][j] = 0;
	//使用空间
	for(i=0;i<row;i++)
	{
		for(j=0;j<colume;j++)
		{
			a[i][row-i-1] = 1;
			a[i][row+i-1] = 1;
			if(i<(row-1) && j<=(row+i-1) && a[i][j]!=NULL && a[i][j+2]!=NULL)
			{
				a[i+1][j+1] = a[i][j]+a[i][j+2];
			}
		}
	}
    for(i=0;i<row;i++)
	{
		for(j=0;j<colume;j++)
		{
			if(a[i][j] == 0)
				cout << ' '; //将0值用空格代替
			else
			cout << a[i][j];
		}
		cout << endl;
	}
	//释放空间
	for(i = 0;i<row;i++)
	{
		delete a[i];
		a[i] = NULL;
	}
	delete [row]a;
	a = NULL;
	system("pause");
	return 0;
}

       这里用到了二维数组的动态建立,需要注意的是,数组用完之后需记得将其释放。另外就是输出,如果直接输出数组a[i][j],那么没有数字的地方会以0填充,看起来并不美观,但是将数组中的0值赋为空格符号,那又涉及到int型和char类型的转换,并不方便,因此考虑不输出0值,在0值处输出一个空格,便解决了该问题。

运行结果如下:

可见,改进后的程序更灵活,输出更美观。

猜你喜欢

转载自blog.csdn.net/elma_tww/article/details/85003312