请编写递归函数,求组合数。 函数原型 double Cmb(int x, int y); 说明:x 和 y 为非负整数,且 x≥y,函数值为组合数 Cxy。 裁判程序 #include <stdio.h> double Cmb(int x, int y); int main() { int m, n; scanf("%d%d", &m, &n); printf("%.10g\n", Cmb(m, n)); return 0; }
时间: 2024-03-20 22:42:38 浏览: 21
好的,以下是递归函数求组合数的代码:
```c
#include <stdio.h>
double Cmb(int x, int y);
int main() {
int m, n;
scanf("%d%d", &m, &n);
printf("%.10g\n", Cmb(m, n));
return 0;
}
double Cmb(int x, int y) {
if (y == 0 || x == y) {
return 1;
} else {
return Cmb(x-1, y-1) + Cmb(x-1, y);
}
}
```
函数 `Cmb` 接收两个非负整数 `x` 和 `y`,并返回组合数 `Cxy`。当 `y` 为 0 或 `x` 等于 `y` 时,直接返回 1,否则递归计算 `C(x-1, y-1)` 和 `C(x-1, y)` 的和。
相关问题
6-4 求组合数(高效递归版)分数 10 全屏浏览题目 作者 李祥 单位 湖北经济学院 请编写递归函数,求组合数。 函数原型 double Cmb(int x, int y); 说明:x 和 y 为非负整数,且 x≥y,函数值为组合数 Cxy。 裁判程序 #include <stdio.h> double Cmb(int x, int y); int main() { int m, n; scanf("%d%d", &m, &n); printf("%.10g\n", Cmb(m, n)); return 0; }
下面是递归实现的代码:
```c++
double Cmb(int x, int y) {
if (y == 0 || y == x) {
return 1.0;
} else {
return Cmb(x - 1, y - 1) + Cmb(x - 1, y);
}
}
```
这里采用了递归的思想,将组合数的求解转化为了子问题的求解。当 y = 0 或 y = x 时,C(x, y) 的值为 1;否则,C(x, y) 的值等于 C(x-1, y-1) + C(x-1, y)。
需要注意的是,为了避免浮点数精度的问题,这里返回的是 double 类型的值。
用CPP代码实现: 自定义递归函数求组合数
可以使用以下的 CPP 代码来自定义递归函数求组合数:
```cpp
#include <iostream>
using namespace std;
int nCr(int n, int r) {
if(r == 0 || r == n) {
return 1;
} else {
return nCr(n - 1, r - 1) + nCr(n - 1, r);
}
}
int main() {
int n = 5, r = 2;
int result = nCr(n, r);
cout << "The value of C(" << n << ", " << r << ") is " << result << endl;
return 0;
}
```
在上面的代码中,我们定义了一个递归函数 `nCr`,它接受两个参数 `n` 和 `r`,分别表示组合数 C(n,r) 中的 n 和 r。如果 r 等于 0 或 n,那么 C(n,r) 的值为 1。否则,我们使用递归计算 C(n-1,r-1) 和 C(n-1,r) 的值,并将它们相加得到 C(n,r) 的值。
在 `main` 函数中,我们以 n=5, r=2 为例调用 `nCr` 函数,并输出计算结果。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)