c - 对问题和代码段的解释

标签 c

Link to the problem

#include<stdio.h>

int factorial(int num)
{
    int result = 1;
    for(int i = 2; i <= num; i++)
    {
        result *= i;
    }
    return result;
}

int comb(int n, int p)
{
    return factorial(n)/(factorial(p)* factorial(n-p));
}
int main()
{
    int n, p;
    printf("%d",comb(5,2));
}

如何根据值 5,2 计算组合? 程序背后的逻辑是什么?

最佳答案

为什么 5 和 2 的输出是 10?

n!表示the factorial of n 。在这种情况下n = 5n! = 5 * 4 * 3 * 2 * 1 = 120

p! = 2(n - p)! = 6 .

因此你有120 / (2 * 6) ,这给了我们 10。

阶乘函数到底是如何工作的?

计算 n 的阶乘时,首先计算一个名为 result 的变量设置为1 .

然后这个result变量与 2 中的每个数字相乘至n在 for 循环内,结果为

result = 1 * 2 * 3 * ... * n

要求用户输入np

您可能还想向用户询问号码 np :

int main()
{
    int n, p;
    printf("Enter n and p comma seperated: ");
    scanf("%d, %d", &n, &p);
    printf("The result is %d\n", comb(n,p));
}

示例:

Enter n and p comma seperated: 5, 2
The result is 10

关于c - 对问题和代码段的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52741449/

相关文章:

c - C源文件包含自己的头文件有什么好处

c - GCC 上的 Makefile for C

c - 在 C 中使用 execve() 调用 "pbmtextps"失败?

c - MPI 矩阵乘法与分散聚集

c - 第九条诫命是什么意思?

C 语言,检查参数是否是 shell 内置命令

c - 如何求树中节点的最大和

c - 如何将指针中的值保存到 char 数组中?

c - *(a+b) 和 (*a+b) 有什么区别

c - 带有无效定界符的字符串标记化