原文: https://beginnersbook.com/2015/02/c-program-to-calculate-and-print-the-value-of-npr/
在下面的程序中,我们根据给定的n和r值计算 nPr 的值。 nPr 也可以表示为P(n, r)。P(n, r)的公式是n! /(n - r)!,例如 P(6, 2)= 6! /(6-2)! => 720/24 = 30。我们在下面的 C 程序中实现了相同的逻辑。
#include <stdio.h>void main(){int n, r, npr_var;printf("Enter the value of n:");scanf("%d", &n);printf("\nEnter the value of r:");scanf("%d", &r);/* nPr is also known as P(n,r), the formula is:* P(n,r) = n! / (n - r)! For 0 <= r <= n.*/npr_var = fact(n) / fact(n - r);printf("\nThe value of P(%d,%d) is: %d",n,r,npr_var);}// Function for calculating factorialint fact(int num){int k = 1, i;// factorial of 0 is 1if (num == 0){return(k);}else{for (i = 1; i <= num; i++){k = k * i;}}return(k);}
输出:
Enter the value of n:5Enter the value of r:2The value of P(6,2) is: 30
