Basic Pascal Tutorial/Chapter 4/Recursion/zh CN

From Lazarus wiki
Jump to navigationJump to search

български (bg) English (en) français (fr) 日本語 (ja) 中文(中国大陆) (zh_CN)

4E - 递归调用 (原作者: Tao Yue, 状态: 未更改)

递归较之难以掌握,不过,一旦你了解后,它变得很容易。本章将涉及递归知识。

递归是指允许一个函数或过程调用自身。调用自身,直到达到限制。

Summation(求和)函数,数学中通过一个大写的Sigma]来指定。常见的递归例子:

function Summation (num : integer) : integer;
begin
  if num = 1 then
    Summation := 1
  else
    Summation := Summation(num-1) + num
end;

假设你求3的和。

a := Summation(3);
  • Summation(3) 变成 Summation(2) + 3
  • Summation(2) 变成 Summation(1) + 2
  • 为1时, 递归停止,变为 1
  • Summation(2) 变成 1 + 2 = 3
  • Summation(3) 变成 3 + 3 = 6
  • a 为 6

Recursion works backward until a given point is reached at which an answer is defined, and then works forward with that definition, solving the other definitions which rely upon that one.

All recursive procedures/functions should have some sort of test so stop the recursion. Under one condition, called the base condition, the recursion should stop. Under all other conditions, the recursion should go deeper. In the example above, the base condition was if num = 1. If you don't build in a base condition, the recursion will either not take place at all, or become infinite.

递归,常常是把解决原问题按顺序逐次调用同一“子程序”(过程)去处理,最后一次调用得到已知数据,执行完该次调用过程的处理,将结果带回,按“先进后出”原则,依次计算返回。

递归表现在处理问题的强大能力。然而,如同循环一样,递归也会带来无终止调用的可能性,因此,在设计递归过程(函数)时,必须考虑递归调用的终止问题,就是递归调用要受限于某一条件,而且要保证这个条件在一定情况下肯定能得到满足。

在上面的例子中,终止递归的条件是num=1。如果没有返回条件,递归要么不会发生,要么变得无限大。

上一页 目录 下一页