用C++写用递归算法求10的阶乘
时间: 2023-05-22 09:04:15 浏览: 82
下面是用 C 写的递归算法求10的阶乘的代码:
```
#include<stdio.h>
int fact(int n) {
if (n == 0) { // 边界条件
return 1;
} else {
return n * fact(n - 1); // 递归调用
}
}
int main() {
int n = 10;
int result = fact(n);
printf("%d的阶乘为%d\n", n, result);
return 0;
}
```
这段代码的输出结果是:
```
10的阶乘为3628800
```
相关问题
c++递归算法求阶乘
C++递归算法求阶乘的实现如下:
```cpp
#include <iostream>
int factorial(int n) {
// 基线条件,当n为0或1时,直接返回1
if (n == 0 || n == 1) {
return 1;
}
// 递归调用,将问题规模缩小,求解n-1的阶乘
return n * factorial(n - 1);
}
int main() {
int n;
std::cout << "请输入一个非负整数:";
std::cin >> n;
std::cout << n << "的阶乘是:" << factorial(n) << std::endl;
return 0;
}
```
以上代码中,`factorial`函数使用递归的方式来求解阶乘。当输入的n为0或1时,直接返回1作为基线条件。否则,递归调用`factorial`函数来求解n-1的阶乘,并将结果与n相乘返回。
递归算法求阶乘GCC9.3
递归算法是一种自我调用的算法,通过将问题分解为更小的子问题来解决。对于求阶乘的递归算法,可以定义如下:
```c++
#include <iostream>
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int num = 5;
int result = factorial(num);
std::cout << "The factorial of " << num << " is: " << result << std::endl;
return 0;
}
```
在上述代码中,`factorial` 函数通过递归调用自身来计算阶乘。当 `n` 的值为 0 或 1 时,递归终止,返回 1。否则,递归调用 `factorial(n - 1)` 来计算 `n` 的阶乘。
运行上述代码,将输出 `The factorial of 5 is: 120`,表示 5 的阶乘为 120。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)