Go homepage(回首页) Upload pictures (上传图片) Write articles (发文字帖)
The author:(作者)aaapublished in(发表于) 2014/7/19 0:09:53 Delphi函数的递归调用
函数的递归调用在Object Pascal 中,过程或函数必须先说明再调用。以上规则在递归调用时属于例外情况。所谓递归调用,是指函数A 调用函数B,而函数B 又调用函数A 的情况,或是指一个函数调用自身的特殊情况。在递归调用中,函数要进行前置,即在函数或过程的标题部分最后加上保留字Forward。下文的例子是一个递归调用的典型例子: program Project1;{$APPTYPE CONSOLE}varAlpha:Integer;procedure Test2(var A:Integer);forward;//Test2 被说明为前置过程procedure Test1(var A:Integer);beginA:=A-1;if A>0 thenTest2(A); //经前置说明,调用未执行的过程Test2writeln(A);end;procedure Test2(var A:Integer); //经前置说明的Test2 的执行部分beginA:=A div 2;if A>0 thenTest1(A); //在Test2 中调用已执行的过程Test1end;beginAlpha := 15; //给Alpha 赋初值Test1(Alpha); //第1 次调用Test1,递归开始end.程序开始时给Alpha 赋初值,并实现先减1 再除2 的循环递归调用,直到Alpha 小于0 为止。
赞