C++ 程式使用階乘計算組合


以下是使用階乘計算組合的示例。

示例

 線上演示

#include <iostream>
using namespace std;
int fact(int n) {
   if (n == 0 || n == 1)
   return 1;
   else
   return n * fact(n - 1);
}
int main() {
   int n, r, result;
   cout<<"Enter n : ";
   cin>>n;
   cout<<"\nEnter r : ";
   cin>>r;
   result = fact(n) / (fact(r) * fact(n-r));
   cout << "\nThe result : " << result;
   return 0;
}

輸出

Enter n : 10
Enter r : 4
The result : 210

在上述程式中,程式碼位於 fact() 函式中,用於計算數字的階乘。

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

在 main() 函式中,使用者輸入兩個組合數。變數“result”將儲存使用階乘計算的組合值。

cout<<"Enter n : ";
cin>>n;
cout<<"\nEnter r : ";
cin>>r;
result = fact(n) / (fact(r) * fact(n-r));

更新時間:2020 年 6 月 26 日

872 次瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.