问:如何在批量编程中将此Fibonacci序列转换为数组?

时间:2016-12-02 00:06:18

标签: arrays batch-file fibonacci

脚本成功计算了斐波那契序列,但我不知道如何将数字转换为数组。

`Title Fibonacci数组     @echo关闭     setlocal enableDelayedExpansion

:Fibonacci
setlocal
    ::C=current L=last S=Swap
    set C=1
    set L=0

    for /l %%G in (1,1,30) do (
        set S=!C!
        set /a C+=!L! & Call :Array !C!
        set L=!S!
)

:Array
    ::Here is where you create the array
    set i=-1

    for %%X in (%1 %2 %3 %4 %5 %6 %7 %8 %9) Do (
        set /a i+=1
        set /a Fib[!i!]=%%X
)   
    set index=!i!

    for /l %%X in (0,1,!index!) do (
        echo !Fib[%%X]!

)
pause>nul
endlocal`

3 个答案:

答案 0 :(得分:2)

Title Fibonacci array
@echo off
setlocal enableDelayedExpansion

:Fibonacci

    ::C=current L=last S=Swap
    set C=1
    set L=0

    set i=-1
    for /l %%G in (1,1,30) do (
        set S=!C!
        set /a C+=L

        rem Here is where you create the array,
        set /a i+=1
        set /a Fib[!i!]=C

        set L=!S!
    )
    set index=!i!


:ShowArray

    for /l %%X in (0,1,!index!) do (
        echo %%X- !Fib[%%X]!
    )

pause>nul
endlocal

编辑更简单的方法

@echo off
Title Fibonacci array
setlocal EnableDelayedExpansion

set N=30

:Fibonacci

    set /A i=0, j=1, Fib[0]=1, Fib[1]=1

    for /L %%G in (2,1,%N%) do set /A Fib[%%G]=Fib[!i!]+Fib[!j!], i=j, j+=1

:ShowArray

    for /L %%X in (1,1,%N%) do echo %%X- !Fib[%%X]!

pause>nul

答案 1 :(得分:0)

Title Fibonacci array
@echo off & setlocal EnableDelayedExpansion

:Fibonacci
::set counter and array index
set/a Count=30, i=0, j=1
set/a F[!i!]=1, F[!j!]=1

echo F[!i!]=1
echo F[!j!]=1
::Calculate the rest and display
for /l %%N in (2,1,%Count%) do (
    set /A F[%%N]=F[!i!]+F[!j!] 
    echo F[%%N]=!F[%%N]!
    set /A i=j, j+=1
)
  

我通过在计算剩余序列的同时显示它来使它更优雅

答案 2 :(得分:0)

其中:跟踪我们添加了前两个值的次数,例如:0 1 1 2 3 5 8 13 21。 。 。 。如果which = 4,则0 + 1 = 1第一次1 + 1 = 2是第二次2 + 1 = 3是第三次,3 + 2 = 5是第四次... 上一页 now1 只是用来跟踪应添加到哪个名称的名称。 。 。从斐波那契开始,.rest逻辑很常见

@echo off
setlocal enabledelayedexpansion
goto:main

:fibo 
    if %~1 equ !%~4! (
        goto:eof
    )
    set /a prevhere=!%~3!
    set /a %~3=!%~3!+!%~2!
    set /a %~2=!prevhere!
    set /a %~4=!%~4!+1
    call:fibo %~1 %~2 %~3 %~4
    enter code here

goto:eof

:main
setlocal
    set /a which=1
    set /a now1=1
    set /a prev1=0
    call:fibo %2 prev1 now1 which
    echo %2th fibo number = !now1!
endlocal
goto:eof