编写求n!.的函数f(int n)
时间: 2023-06-12 13:04:49 浏览: 93
以下是求n!的函数f(int n)的C++代码实现:
```cpp
#include <iostream>
using namespace std;
int f(int n) {
int res = 1;
for (int i = 2; i <= n; i++) {
res *= i;
}
return res;
}
int main() {
int n;
cin >> n;
cout << f(n) << endl;
return 0;
}
```
该函数使用for循环从2到n,将每个数字乘到结果中,最终返回结果。需要注意的是,当n为0或1时,n!的结果为1。
相关问题
编写求 n!的函数 f(int n),在主函数中输入两个整数 m、n,然后调用函数求:,代码
C++代码如下:
```
#include <iostream>
using namespace std;
// 求n的阶乘
int f(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * f(n-1);
}
}
int main() {
int m, n;
cout << "请输入两个整数m和n(m<n):";
cin >> m >> n;
// 求m!和n!
int fm = f(m);
int fn = f(n);
cout << "m! = " << fm << endl;
cout << "n! = " << fn << endl;
// 求n!/m!
int result = fn / fm;
cout << "n!/m! = " << result << endl;
return 0;
}
```
输入两个整数m和n,输出m!、n!和n!/m!的值。
编写求n!的函数f(int n),在主函数中输入两个整数m、n,然后调用函数求: C=m!/n!(m -n)!
好的,我可以编写这个函数。以下是代码示例:
```c++
#include <iostream>
using namespace std;
int f(int n) {
if (n <= 1) {
return 1;
} else {
return n * f(n - 1);
}
}
int main() {
int m, n;
cout << "请输入两个整数m和n,以空格分隔:" << endl;
cin >> m >> n;
int C = f(m) / (f(n) * f(m - n));
cout << "C=" << C << endl;
return 0;
}
```
这个函数使用递归的方式计算n的阶乘。在主函数中,首先输入两个整数m和n,然后调用函数计算组合数C。最后输出结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.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)