原文: https://beginnersbook.com/2015/02/c-program-to-calculate-and-print-the-value-of-ncr/

    在下面的程序中,我们计算并显示 nCr 的值。 nCr 也可以表示为 C(n, r)

    公式为:

    C(n, r)= n! /(r!(n - r)!),对于0 <= r <= n。这里!代表阶乘。例如:C(6, 2)= 6! /(2! * (6-2)!) => 720 /(2 * 24) => 15

    我们在以下程序中进行了相同的计算。

    1. #include <stdio.h>
    2. int fact(int num);
    3. void main()
    4. {
    5. int n, r, ncr_var;
    6. printf("Enter the value of n:");
    7. scanf("%d", &n);
    8. printf("\nEnter the value of r:");
    9. scanf("%d", &r);
    10. /* ncr is also represented as C(n,r), the formula is:
    11. * C(n,r) = n! / ( r!(n - r)! ). For 0 <= r <= n.
    12. */
    13. ncr_var = fact(n) / (fact(r) * fact(n - r));
    14. printf("\nThe value of C(%d,%d) is: %d",n,r,ncr_var);
    15. }
    16. /* This function is used to find the
    17. * factorial of given number num
    18. */
    19. int fact(int num)
    20. {
    21. int k = 1, i;
    22. // factorial of 0 is 1
    23. if (num == 0)
    24. {
    25. return(k);
    26. }
    27. else
    28. {
    29. for (i = 1; i <= num; i++)
    30. {
    31. k = k * i;
    32. }
    33. }
    34. return(k);
    35. }

    输出:

    1. Enter the value of n:
    2. 5
    3. Enter the value of r:
    4. 2
    5. The value of C(6,2) is: 15