|
#include<iostream>
using std::cin;
using std::cout;
using std::endl;
#include <iomanip>
using std::setw;
void nextLevel( int a[], int i ,int level )
{
int j;
int k;
for( k=(level-i);k>0;k--)//在每一行前面插數空白,空白數與階數成反比
{
cout<<" ";
}
for(j=1; j<=i;j++)
{
cout << setw (4);//設定一次輸出的字元寬度
cout<<a[j];//輸出array內容
}
a[i+1]=1;//這個東西是最外圍的那個1,然後用下面那個迴圈向內逼近!算出巴斯卡
for( j=i; j>=2; j--)
{
a[j]=a[j-1]+a[j]; // 巴斯卡三角形的定義: 階層 i+1 的a[j] 等於階層 i 的a[j-1]+a[j]
}
}
void displayPascal( int a[], int level, int i )
{
int b[100];//這個變數的設定,是用來存放空白數
for ( int x=level ;x<=i ;x-- )
{
cout << b[x]<< " ";//跟上面的計算類似...空白幾個,就會用到幾個array
cout <<a[1];//排好空白後,輸出第一個數字1
}
cout << endl;
}
void pascalTriangle( int level )//這個函數其實沒幹麻,只是中間的舖道,把該設定的值設定好
{
int a[100];
a[1] = 1;
for ( int i = 1; i < level; i++ )// 印巴斯卡三角形 1~level 層
{
nextLevel( a, i, level );
displayPascal( a, level, i );
}
}
int main()
{
int level;
const int Low = 1;
const int High = 13;
do
{
cout << "How many levels? (1-13): ";
cin >> level;
level = level + 1;
}
while ( level < Low || level > High );
pascalTriangle( level );
return 0;
} |
|