小白求助递归函数
#include <stdio.h>int combination(int n,int r)
{
if (r > 1)
return (combination(n-1,r-1) + combination(n-1,r));
else if (r == 1)
return n;
else if (r == n || r == 0)
return 1;
}
int main(void)
{
int n,r;
scanf("%d%d",&n,&r);
printf("%d",combination(n,r));
return 0;
}
编写程序,从n个不同整数中取出r个整数的组合数Crn(使用递归函数) 问题描述:
这个问题要求编写一个递归函数来计算从n个不同整数中取出r个整数的组合数Crn。
解决方案:
递归函数的实现如下:
#include <stdio.h>
int combination(int n, int r)
{
if (r > 1)
return (combination(n - 1, r - 1) + combination(n - 1, r));
else if (r == 1)
return n;
else if (r == n || r == 0)
return 1;
}
int main(void)
{
int n, r;
scanf("%d%d", &n, &r);
printf("%d", combination(n, r));
return 0;
}
在递归函数combination中,我们使用了三个if语句来处理不同的情况:
1. 如果r大于1,我们将问题分解为两个子问题,分别是从n-1个整数中取出r-1个整数的组合数和从n-1个整数中取出r个整数的组合数,然后将它们相加得到结果。
2. 如果r等于1,我们直接返回n,因为从n个整数中取出1个整数的组合数就是n本身。
3. 如果r等于n或者r等于0,我们直接返回1,因为从n个整数中取出n个整数或者取出0个整数的组合数都只有一种情况。
在主函数main中,我们首先读取输入的n和r,然后调用递归函数combination来计算组合数,并将结果输出。
希望能帮到你! #include <stdio.h>
int combination(int n, int r) {
if (r > 1)
return (combination(n - 1, r - 1) + combination(n - 1, r));
else if (r == 1)
return n;
else if (r == n || r == 0)
return 1;
}
int main(void) {
int n, r;
printf("Enter the values of n and r: ");
scanf("%d%d", &n, &r);
if (n >= r) {
int result = combination(n, r);
printf("The combination C(%d, %d) is: %d\n", n, r, result);
} else {
printf("Invalid input! n should be greater than or equal to r.\n");
}
return 0;
}
This program calculates the combination C(n, r) using a recursive function. The combination function recursively calculates the combination based on the given formula. In the main function, the user is prompted to enter the values of n and r, and then the combination is calculated and printed if the input is valid.
Please note that it's important to handle cases where n is less than r or negative numbers to ensure the correctness and validity of the calculations.
球一个最佳答案谢谢啦!这对我非常重要!{:10_254:}{:10_254:}{:10_254:}
页:
[1]