可以递归调用函数,以确保即使重用了变量名,递归的每个级别也都可以使用自己的变量集。
当斐波那契算法达到一个大于或等于给定输入数字的数字时,递归停止,该示例以数字0和1开头,:myFibo函数递归调用自身以计算下一个斐波那契数,直到找到大于或等于1000000000的斐波那契数。
链接:https://www.learnfk.comhttps://www.learnfk.com/batch-script/batch-script-recursive-functions.html
来源:LearnFk无涯教程网
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.
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)