c++求阶乘
时间: 2025-04-21 07:40:33 浏览: 57
### 使用C++编写计算阶乘的程序
#### 方法一:递归方法
通过定义一个名为 `factorial` 的函数,该函数接受一个整数参数并返回其阶乘值。对于基础情况,当输入为 0 或者 1 时直接返回 1;其他情况下则按照公式 \(n! = n \times (n-1)!\) 进行递归调用。
```cpp
#include <iostream>
using namespace std;
int factorial(int n) {
if (n == 0 || n == 1) { // 基础条件
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int number;
cout << "请输入要计算阶乘的正整数: ";
cin >> number;
if (number >= 0) {
cout << number << "! = " << factorial(number) << endl;
} else {
cout << "错误:负数没有阶乘." << endl;
}
return 0;
}
```
此段代码实现了基于递归算法的阶乘计算器[^2]。
#### 方法二:迭代方法
另一种常见的做法是采用循环结构来逐步累乘直到达到目标数值为止。这种方法避免了栈溢出的风险,在处理较大范围内的数据时更加稳定可靠。
```cpp
#include <iostream>
using namespace std;
unsigned long long iterativeFactorial(unsigned int num){
unsigned long long result = 1;
while(num > 1){
result *= num--;
}
return result;
}
int main(){
unsigned int inputNum;
cout<<"请输入想要计算的非负整数:";
cin>>inputNum;
cout<<inputNum<<"!="<<iterativeFactorial(inputNum)<<endl;
return 0;
}
```
上述代码展示了使用迭代法实现阶乘运算的方式[^5]。
#### 注意事项
由于阶乘增长速度极快,即使是相对较小的数字也可能导致最终结果超出标准整形变量所能表示的最大限度。因此建议在实际应用中考虑使用更大容量的数据类型如 `long long` 或者第三方库提供的大整数类来进行存储和操作。
阅读全文
相关推荐















