遞迴列印楊輝三角

來源:互聯網
上載者:User

/*05-06-10 21:40
遞迴列印楊輝三角:這裡要知道一個定論:
                        1
     1  1
    1  2  1
   1  3  3  1
  1  4  6  4  1
 1  5  10 10 5  1 

 i(>=0)代表第幾行,j(>=0)代表第幾個位置的數 規律如下
 第4行第一個數為3:3!/(2!*(3-2)!) =3  數從0開始 ,行業從0開始
 第4行第0個數為3: 3!/(0!*(3-0)!)=1
  楊輝三角滿足一個組合公式:n!/(!m*!(n-m)) 利用此公式就可求出每一個數
  公式如下:
  某個位置楊輝三角數= 當前行數的階乘(從0開始)/( 列的位置數組成的階乘從0開始) *(行數-列組成數的階乘) )
*/
#include<iostream>
using namespace std;

int fun(int n)       //n代表行數
{
    if (n==0 )
    {
        return 1;
    }
    else
    {
        return n*fun(n-1);
    }
}
int main()
{
    int n;
    int i,j;
    int c;       //儲存楊輝三角的臨時變數
   
    int curline;   //當前行數的階乘,從0開始
    int backline;   //行數-列位置所構成的階乘
    int position;   //行的第幾個位置的階乘
    
    cout<<" 請輸入你要輸出楊輝三角的行數:";
    cin>>n;
   
    for (i=0; i<=n; i++)
    {
        for(int k=i;k<n;k++)  cout<<"   "; //輸出前面的空格(2),和後面的空格要好好配合
        for (j=0; j<=i; j++)            //等號要注意
        {
            curline   = fun(i);            //當前行數的階乘,從0開始
            backline  = fun(i-j);          //行數-列位置所構成的階乘
            position  = fun(j);            //行的第幾個位置的階乘
           
            c =  curline/(backline * position);   //具體位置楊輝三角的值
            cout<<c<<"     ";   //5個空格
        }

        cout<<endl;                         //輸出一行換行處理
    }
   
    cout<<endl;
    
    system("pause");
    return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.