C++ 程式使用遞迴來計算數字階乘


非負整數 n 的階乘是對於小於或等於 n 的所有正整數的乘積。

例如:7 的階乘為 5040。

7! = 7 * 6 * 5 * 4 * 3 * 2 *1
7! = 5040

讓我們看看如何使用遞迴來計算數字的階乘。

示例

 線上演示

#include <iostream>
using namespace std;
int fact(int n) {
   if ((n==0)||(n==1))
   return 1;
   else
   return n*fact(n-1);
}
int main() {
   cout<<"Factorial of 5 is "<<fact(5)<<endl;
   cout<<"Factorial of 3 is "<<fact(3)<<endl;
   cout<<"Factorial of 7 is "<<fact(7)<<endl;
   return 0;
}

輸出

Factorial of 5 is 120
Factorial of 3 is 6
Factorial of 7 is 5040

在以上程式中,函式 fact() 是一個遞迴函式。main() 函式使用要計算其階乘的數字呼叫 fact()。以下程式碼片段說明了這一點。

cout<<"Factorial of 5 is "<<fact(5)<<endl;
cout<<"Factorial of 3 is "<<fact(3)<<endl;
cout<<"Factorial of 7 is "<<fact(7)<<endl;

如果該數字為 0 或 1,則 fact() 返回 1。如果該數字是任何其他數字,則 fact() 使用值 n-1 遞迴呼叫自身。fact() 除了遞迴呼叫自身外,還將 n 與遞迴呼叫 fact(n-1) 相乘。這產生了以下結果。

n*(n-1)*(n-2)....3*2*1 or the factorial of n

以下程式碼片段說明了這一點。

int fact(int n) {
   if ((n==0)||(n==1))
   return 1;
   else
   return n*fact(n-1);
}

更新於:2020-6-24

1K+ 檢視

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.