阶乘函数c++完整代码
时间: 2024-11-18 09:14:16 浏览: 49
在C++中,你可以使用递归、迭代或者其他优化技巧来编写阶乘函数。这里给出两个例子:
**递归实现(注意,对于大数值,这种方法可能会导致栈溢出):**
```cpp
#include <iostream>
unsigned long long factorial_recursive(unsigned int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial_recursive(n - 1);
}
}
int main() {
unsigned int n;
std::cout << "请输入一个非负整数:";
std::cin >> n;
std::cout << "阶乘结果是:" << factorial_recursive(n) << std::endl;
return 0;
}
```
**迭代实现,优化了大数处理:**
```cpp
#include <iostream>
#include <vector>
unsigned long long factorial_iterative(unsigned int n) {
std::vector<unsigned long long> fac(100000, 1); // 初始化数组存储前n的阶乘值
for (unsigned int i = 2; i <= n; ++i) {
fac[i] = fac[i - 1] * i;
}
return fac[n];
}
int main() {
unsigned int n;
std::cout << "请输入一个非负整数:";
std::cin >> n;
std::cout << "阶乘结果是:" << factorial_iterative(n) << std::endl;
return 0;
}
```
在这段代码里,迭代版本通过预先计算并存储部分阶乘值,解决了递归的大数问题。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.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)