使用遞迴關係計算 nCr 的 C++ 程式


這是一個 C++ 程式,用於使用 nCr 的遞迴關係來計算組合。

演算法

Begin
   function CalCombination():
      Arguments: n, r.
      Body of the function:
      Calculate combination by using
      the formula: n! / (r! * (n-r)!.
End

示例

#include<iostream>
using namespace std;
float CalCombination(float n, float r) {
   int i;
      if(r > 0)
         return (n/r)*CalCombination(n-1,r-1);
      else
   return 1;
}
int main() {
   float n, r;
   int res;
   cout<<"Enter the value of n: ";
   cin>>n;
   cout<<"Enter the value of r: ";
   cin>>r;
   res = CalCombination(n,r);
   cout<<"\nThe number of possible combinations are: nCr = "<<res;
}

輸出

Enter the value of n: 7
Enter the value of r: 6
The number of possible combinations are: nCr = 2

更新日期: 30-Jul-2019

513 瀏覽

開啟您的 職業 生涯

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.