Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ คำนวณ Combinations (nCr) ด้วยความสัมพันธ์แบบเรียกซ้ำ (Recurrence Relation)


นี่คือโปรแกรม C++ สำหรับคำนวณ Combinations (nCr) ด้วยความสัมพันธ์แบบเรียกซ้ำ (Recurrence Relation)

อัลกอริทึม

เริ่มต้น    ฟังก์ชัน CalCombination():       อาร์กิวเมนต์: n, r       ส่วนตัวของฟังก์ชัน:       คำนวณ combination โดยใช้       สูตร: n! / (r! * (n-r)!. จบ

ตัวอย่างโค้ด

#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