递归与复杂数据类型编程详解
1. 递归编程
递归是指函数调用自身的编程技巧,它是一种强大的工具,但使用时需要遵循一定规则。
1.1 阶乘计算的递归实现
经典的递归问题是计算阶乘。阶乘函数的定义如下:
- 当 ( n = 1 ) 时,( f(n) = 1 )
- 否则,( f(n) = n \times f(n - 1) )
以下是实现阶乘计算的代码:
/**
* Compute factorial recursively
* (the basic recursive example)
*/
#include <stdio.h>
/**
* Compute factorial
*
* @param x The number to compute the factorial of
* @returns the factorial
*/
int factor(const int x) {
if (x == 1)
return (1);
return (x * factor(x-1));
}
int main()
{
int result = factor(5);
printf("5! is %d\n", result);
return (0);
}
在计算 factor(5) 时,过程如下:
1. 调用 factor(5) ,需要
超级会员免费看
订阅专栏 解锁全文
758

被折叠的 条评论
为什么被折叠?



