搜索
熱搜: 活動 交友 discuz
查看: 4324|回復: 0
打印 上一主題 下一主題

[教學] 巴斯卡三角形的 C++程式設計

[複製鏈接]
跳轉到指定樓層
1#
發表於 2007-8-14 04:37:33 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
  1. #include<iostream>
  2. using std::cin;
  3. using std::cout;
  4. using std::endl;

  5. #include <iomanip>
  6. using std::setw;

  7. void nextLevel( int a[], int i ,int level )
  8. {        
  9.         int j;
  10.         int k;
  11.         for( k=(level-i);k>0;k--)//在每一行前面插數空白,空白數與階數成反比
  12.         {
  13.             cout<<"  ";
  14.     }

  15.         for(j=1; j<=i;j++)
  16.         {
  17.                 cout << setw (4);//設定一次輸出的字元寬度
  18.                 cout<<a[j];//輸出array內容
  19.         }
  20.         
  21.         a[i+1]=1;//這個東西是最外圍的那個1,然後用下面那個迴圈向內逼近!算出巴斯卡

  22.                 for( j=i; j>=2; j--)
  23.                 {
  24.                         a[j]=a[j-1]+a[j]; // 巴斯卡三角形的定義: 階層 i+1 的a[j] 等於階層 i 的a[j-1]+a[j]
  25.                 }
  26. }

  27. void displayPascal( int a[], int level, int i )
  28. {
  29.         int b[100];//這個變數的設定,是用來存放空白數
  30.                 for ( int x=level ;x<=i ;x-- )
  31.         {
  32.                 cout << b[x]<< " ";//跟上面的計算類似...空白幾個,就會用到幾個array
  33.                 cout <<a[1];//排好空白後,輸出第一個數字1
  34.         }
  35.                 cout << endl;
  36. }



  37. void pascalTriangle( int level )//這個函數其實沒幹麻,只是中間的舖道,把該設定的值設定好
  38. {
  39.         int a[100];
  40.         
  41.         a[1] = 1;
  42.         
  43.         for ( int i = 1; i < level; i++ )// 印巴斯卡三角形 1~level 層
  44.         {
  45.                 nextLevel( a, i, level );

  46.                 displayPascal( a, level, i );
  47.         }

  48.                         
  49. }


  50. int main()
  51. {
  52.         int level;
  53.         const int Low = 1;
  54.         const int High = 13;

  55.         do
  56.         {
  57.                 cout << "How many levels? (1-13): ";
  58.                 cin >> level;
  59.                 level = level + 1;
  60.         }
  61.         while ( level < Low || level > High );

  62.         pascalTriangle( level );

  63.         return 0;  
  64. }
複製代碼
您需要登錄後才可以回帖 登錄 | 註冊

本版積分規則

本論壇為非營利之網路平台,所有文章內容均為網友自行發表,不代表論壇立場!若涉及侵權、違法等情事,請告知版主處理。


Page Rank Check

廣告刊登  |   交換連結  |   贊助我們  |   服務條款  |   免責聲明  |   客服中心  |   中央分站

手機版|中央論壇

GMT+8, 2026-6-4 06:33 , Processed in 0.029950 second(s), 16 queries .

Powered by Discuz!

© 2005-2015 Copyrights. Set by YIDAS

快速回復 返回頂部 返回列表