int Fact(int n) { /********* Begin *********/ //使用递归计算 n 的阶乘 /********* End *********/ }
时间: 2025-05-29 18:53:23 浏览: 13
### 实现递归阶乘函数的代码示例
#### 头文件设计
头文件 `fact.h` 用于声明函数原型。通过宏保护机制防止多次包含同一头文件。
```c++
// fact.h
#ifndef FACT_H
#define FACT_H
int Fact(int n);
#endif // FACT_H
```
此段代码定义了一个名为 `Fact` 的函数,接受一个整数参数 `n` 并返回其阶乘值[^1]。
---
#### 源文件实现
在 `fact.cpp` 文件中实现递归逻辑。如果输入为 `0` 或 `1`,直接返回 `1`;否则调用自身计算 `(n-1)!` 并与其相乘得出最终结果。
```cpp
// fact.cpp
#include "fact.h"
int Fact(int n) {
if (n == 0 || n == 1) { // Base case
return 1;
}
return n * Fact(n - 1); // Recursive call
}
```
这段代码严格遵循递归结构:简单情况(base case)处理以及复杂情况下向更简单的子问题转化的过程[^2]。
---
#### 测试主程序
为了验证该函数的正确性,在 `main.cpp` 中编写测试代码:
```cpp
// main.cpp
#include <iostream>
#include "fact.h"
using namespace std;
int main() {
int number;
cout << "Enter a non-negative integer: ";
cin >> number;
if (number >= 0) {
cout << "Factorial of " << number << " is " << Fact(number) << endl;
} else {
cout << "Error: Factorial is not defined for negative numbers." << endl;
}
return 0;
}
```
此部分允许用户输入任意非负整数,并输出对应的阶乘值。同时加入了错误提示以应对非法输入情形[^3]。
---
### 总结说明
上述实现方式将函数声明与定义分开管理,便于后续维护与扩展。递归方法简洁直观地表达了阶乘公式的本质特性,即 \( n! = n \times (n-1)! \),并妥善处理了边界条件 \( 0! = 1 \)[^4]。
阅读全文
相关推荐



















