1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
......
#include <iostream.h>
#include <iomanip.h>
typedef long (*FunPtr)( long, long );
long Factorial( long value );
long GetElementMethod1( long row, long col );
long GetElementMethod2( long row, long col );
void Output( long step, FunPtr funptr );
// 程序入口点
int main()
{
FunPtr funptr;
// 使用数学公式方法输出杨辉三角
funptr = GetElementMethod1;
Output( 6, funptr );
cout << endl;
// 使用递归输出杨辉三角
funptr = GetElementMethod2;
Output( 6, funptr );
return 0;
}
// 获取当前参数的阶乘值
long Factorial( long value )
{
if ( value == 0 || value == 1 )
return 1;
else
return value * Factorial( value - 1 );
}
// 获取杨辉三角第row行第col列元素的值
long GetElementMethod1( long row, long col )
{
return Factorial( row ) / ( Factorial( row - col ) * Factorial( col ) );
}
// 获取杨辉三角第row行第col列元素的值
long GetElementMethod2( long row, long col )
{
if ( col == 0 || row == col )
return 1;
else
return GetElementMethod2( row - 1, col - 1 ) + GetElementMethod2( row - 1, col );
}
// 输出杨辉三角,step为杨辉三角的阶数。
void Output( long step, FunPtr funptr )
{
for ( int row = 0; row <= step; ++row )
{
for ( int col = 0; col <= row; col++ )
{
cout << setw( 5 ) << funptr( row, col );
}
cout << endl;
}
}