Sign in Join
Wiki copytemporary

Basic Pascal Tutorial/Chapter 4/Recursion/zh CN

English · Français · Български · 中文(中国) · 日本語

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

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

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

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

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

假设你求3的和。

pascal
a := Summation(3);

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。如果没有返回条件,递归要么不会发生,要么变得无限大。

上一页 目录 下一页

From the Free Pascal wiki, page "Basic Pascal Tutorial/Chapter 4/Recursion/zh CN", as it stood on 2022-08-20 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.

Revision 2, last changed by WikiArchive .

Talk about this page

Nobody has opened a bench for this page yet. Sign in to open one.