c++写一个计算组合的函数
时间: 2024-05-10 19:16:42 浏览: 11
可以使用递归来实现计算组合的函数。
组合的公式为:C(n,m) = C(n-1,m-1) + C(n-1,m),其中C(n,m)表示从n个元素中选取m个元素的组合数。
以下是使用递归实现计算组合的函数的示例代码:
```c++
#include <iostream>
using namespace std;
int combination(int n, int m) {
if (m == 0 || m == n) {
return 1;
} else {
return combination(n-1, m-1) + combination(n-1, m);
}
}
int main() {
int n = 5, m = 2;
int result = combination(n, m);
cout << "C(" << n << "," << m << ") = " << result << endl;
return 0;
}
```
在上面的示例代码中,combination函数采用递归的方式来计算组合数。当m等于0或n时,直接返回1,否则按照组合公式计算并返回结果。在main函数中,调用combination函数计算C(5,2)的组合数,并输出结果。
相关问题
使用c++程序调用函数计算组合数
可以使用以下代码来计算组合数:
```c
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n-1);
}
}
int combination(int n, int r) {
return factorial(n) / (factorial(r) * factorial(n-r));
}
int main() {
int n = 5;
int r = 2;
int result = combination(n, r);
printf("C(%d, %d) = %d\n", n, r, result);
return 0;
}
```
这个程序使用了递归来计算阶乘,然后使用阶乘来计算组合数。在这个例子中,我们计算了 C(5, 2) 的值,结果为 10。
用c++写一个rtp流转h264的函数
以下是一个简单的 C++ 函数,将 RTP 流转换为 H.264 编码的视频流:
```cpp
#include <iostream>
#include <fstream>
#include <cstring>
void rtp2h264(const char* rtpFileName, const char* h264FileName)
{
std::ifstream rtpFile(rtpFileName, std::ios::in | std::ios::binary);
std::ofstream h264File(h264FileName, std::ios::out | std::ios::binary);
const int RTP_HEADER_SIZE = 12;
const int H264_NALU_HEADER_SIZE = 4;
char buffer[RTP_HEADER_SIZE + H264_NALU_HEADER_SIZE];
while (rtpFile.read(buffer, RTP_HEADER_SIZE))
{
// skip RTP header and get the H.264 NALU header
rtpFile.read(buffer + RTP_HEADER_SIZE, H264_NALU_HEADER_SIZE);
// calculate the size of the H.264 NALU
int naluSize = rtpFile.gcount() - RTP_HEADER_SIZE - H264_NALU_HEADER_SIZE;
// write the H.264 NALU to the output file
h264File.write(buffer + RTP_HEADER_SIZE + H264_NALU_HEADER_SIZE, naluSize);
}
rtpFile.close();
h264File.close();
}
int main()
{
rtp2h264("input.rtp", "output.h264");
return 0;
}
```
该函数首先打开输入的 RTP 文件和输出的 H.264 文件,然后循环读取 RTP 数据包。对于每个数据包,函数跳过 RTP 头部,然后获取 H.264 NALU 头部。接下来计算 H.264 NALU 的大小,并将其写入输出文件中。最后,函数关闭输入和输出文件。
请注意,此函数仅适用于未加密、未压缩的 RTP 流,并且假定每个 RTP 数据包只包含一个 H.264 NALU。实际的应用程序可能需要更复杂的处理,例如解密、解压缩和组合多个 RTP 数据包。