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

    在下面的程序中,我们根据给定的nr值计算 nPr 的值。 nPr 也可以表示为P(n, r)P(n, r)的公式是n! /(n - r)!,例如 P(6, 2)= 6! /(6-2)! => 720/24 = 30。我们在下面的 C 程序中实现了相同的逻辑。

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

    输出:

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