Skip to content

Latest commit

 

History

History
55 lines (45 loc) · 1.2 KB

File metadata and controls

55 lines (45 loc) · 1.2 KB

C 程序:计算并打印 nPr 的值

原文: 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 程序中实现了相同的逻辑。

#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 factorial
int fact(int num)
{
    int k = 1, i;
    // factorial of 0 is 1
    if (num == 0)
    {
        return(k);
    }
    else
    {
        for (i = 1; i <= num; i++)
    {
            k = k * i;
	}
    }
    return(k);
}

输出:

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