无涯教程-批处理 - Recursive Functions函数

71 阅读1分钟

可以递归调用函数,以确保即使重用了变量名,递归的每个级别也都可以使用自己的变量集。

当斐波那契算法达到一个大于或等于给定输入数字的数字时,递归停止,该示例以数字0和1开头,:myFibo函数递归调用自身以计算下一个斐波那契数,直到找到大于或等于1000000000的斐波那契数。

myFibo函数的第一个参数是用于存储输出的变量的名称,此变量必须初始化为以Fibonacci开头的数字,并在调用函数时用作当前的Fibonacci编号,并将其设置为后续变量函数返回时的斐波那契数。

@echo off
set "fst=0"
set "fib=1"
set "limit=1000000000"
call:myFibo fib,%fst%,%limit%
echo.The next Fibonacci number greater or equal %limit% is %fib%.
echo.&pause&goto:eof
:myFibo -- calculate recursively
:myFibo -- calculate recursively the next Fibonacci number greater or equal to a limit
SETLOCAL
set /a "Number1=%~1"
set /a "Number2=%~2"
set /a "Limit=%~3"
set /a "NumberN=Number1 + Number2"

if /i %NumberN% LSS %Limit% call:myFibo NumberN,%Number1%,%Limit% (ENDLOCAL IF "%~1" NEQ "" SET "%~1=%NumberN%" )goto:eof

上面的命令产生以下输出。

The next Fibonacci number greater or equal 1000000000 is 1134903170.

参考链接

www.learnfk.com/batch-scrip…