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

โปรแกรม C++ คำนวณแฟกทอเรียลด้วย Recursion (เวอร์ชัน 2)


แฟกทอเรียล n! = n × (n-1) × ... × 1

ตัวอย่าง: 7! = 7×6×5×4×3×2×1 = 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

อธิบาย (คล้าย 1004083119 แต่อธิบายละเอียดกว่า)

fact() เรียกซ้ำ n × fact(n-1) จน n=0 หรือ 1 คืน 1

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

กระบวนการ: n × (n-1) × (n-2) × ... × 3 × 2 × 1

main() เรียกหลายค่า: fact(5), fact(3), fact(7)