写一个用栈实现递归计算阶乘的c++代码
时间: 2023-10-15 08:07:24 浏览: 54
好的,下面是用栈实现递归计算阶乘的c++代码:
```c++
#include <iostream>
#include <stack>
using namespace std;
int factorial(int n) {
stack<int> s;
s.push(n);
int result = 1;
while (!s.empty()) {
int x = s.top();
s.pop();
result *= x;
if (x > 1) {
s.push(x - 1);
}
}
return result;
}
int main() {
int n;
cout << "请输入一个整数:";
cin >> n;
cout << n << "的阶乘是:" << factorial(n) << endl;
return 0;
}
```
希望对您有帮助!
相关问题
用c++完成以下题目:利用递归写出n的阶乘
好的,以下是用C++递归方式实现求n的阶乘的代码:
```c++
#include <iostream>
using namespace std;
int factorial(int n) {
if (n == 0 || n == 1) { // 递归终止条件
return 1;
}
return n * factorial(n-1); // 递归调用
}
int main() {
int n;
cout << "请输入一个正整数n: ";
cin >> n;
int result = factorial(n);
cout << n << "的阶乘是: " << result << endl;
return 0;
}
```
在上述代码中,我们首先声明了一个递归函数 `factorial()`,它的参数是一个整数 `n`,返回值也是一个整数。然后在函数中,我们设置了递归终止条件:当 `n` 为0或1时,阶乘为1,直接返回1。否则,我们用递归方式调用 `factorial()` 函数,传入参数 `n-1`,并将返回的结果与 `n` 相乘,最终得到 `n` 的阶乘。在主函数中,我们接收用户输入的整数 `n`,并调用 `factorial()` 函数计算 `n` 的阶乘,最后输出结果。
注意,递归函数调用时要注意递归深度,如果递归深度过深,可能会导致栈溢出等问题。因此,在实际应用中,需要根据具体情况来设置递归深度或者使用非递归方法实现。
运用c++编写程序,用函数递归调用,计算10!
好的,以下是 C++ 代码实现:
```cpp
#include <iostream>
using namespace std;
int factorial(int n) {
if (n == 1) {
return 1;
} else {
return n * factorial(n-1);
}
}
int main() {
int result = factorial(10);
cout << result << endl; // 输出 3628800
return 0;
}
```
解释一下代码:
- `factorial(n)` 函数用来计算 n 的阶乘,使用递归调用的方式。
- 当 n 等于 1 时,递归结束,返回 1。
- 否则,递归调用 `factorial(n-1)`,并将结果乘以 n。
- `main()` 函数中,调用 `factorial(10)` 来计算 10!,并将结果保存在 `result` 变量中。
- 最后一行输出 `result` 的值,即 10! 的结果。
注意:C++ 中递归调用次数过多可能会导致栈溢出,所以在实际使用时需要注意递归深度的控制。