#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 = 5
和n! = 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
要求用户输入n
和p
您可能还想向用户询问号码 n
和p
:
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/