代码之家  ›  专栏  ›  技术社区  ›  bugmagnet

这个递归的windows cmd脚本有什么问题?阿克曼做得不好

  •  1
  • bugmagnet  · 技术社区  · 15 年前

    我在试着计算阿克曼函数。我要达到的目标是 http://rosettacode.org/wiki/Ackermann_function .

    使用测试脚本,测试04给出了正确的5。然而,测试14给出5而不是6,测试24给出5而不是11。

    我哪里做错了?

    ::echo off
    set depth=0
    :ack
    if %1==0 goto m0
    if %2==0 goto n0
    
    :else
    set /a n=%2-1
    set /a depth+=1
    call :ack %1 %n%
    set t=%errorlevel%
    set /a depth-=1
    set /a m=%1-1
    set /a depth+=1
    call :ack %m% %t%
    set t=%errorlevel%
    set /a depth-=1
    if %depth%==0 ( exit %t% ) else ( exit /b %t% )
    
    :m0
    set/a n=%2+1
    if %depth%==0 ( exit %n% ) else ( exit /b %n% )
    
    :n0
    set /a m=%1-1
    set /a depth+=1
    call :ack %m% %2
    set t=%errorlevel%
    set /a depth-=1
    if %depth%==0 ( exit %t% ) else ( exit /b %t% )
    

    我用这个脚本来测试

    @echo off
    cmd/c ackermann.cmd %1 %2
    echo Ackermann of %1 %2 is %errorlevel%
    

    测试11的样本输出给出:

    >test 1 1
    >set depth=0
    >if 1 == 0 goto m0
    >if 1 == 0 goto n0
    >set /a n=1-1
    >set /a depth+=1
    >call :ack 1 0
    >if 1 == 0 goto m0
    >if 0 == 0 goto n0
    >set /a m=1-1
    >set /a depth+=1
    >call :ack 0 0
    >if 0 == 0 goto m0
    >set/a n=0+1
    >if 2 == 0 (exit 1  )  else (exit /b 1  )
    >set t=1
    >set /a depth-=1
    >if 1 == 0 (exit 1  )  else (exit /b 1  )
    >set t=1
    >set /a depth-=1
    >set /a m=1-1
    >set /a depth+=1
    >call :ack 0 1
    >if 0 == 0 goto m0
    >set/a n=1+1
    >if 1 == 0 (exit 2  )  else (exit /b 2  )
    >set t=2
    >set /a depth-=1
    >if 0 == 0 (exit 2  )  else (exit /b 2  )
    Ackermann of 1 1 is 2
    
    2 回复  |  直到 13 年前
        1
  •  2
  •   Patrick Cuff    15 年前

    将上面的第27行从

    call :ack %m% %2 
    

    call :ack %m% 1
    
        2
  •  0
  •   djna    15 年前

    变量m和n的范围是什么?

    在对:ack的一次调用中设置值,然后递归地再次调用,设置值。你覆盖它们了吗?在基于C和Java的堆栈语言中,局部变量是很好的,递归的每一级都会得到新的变量。CMD中发生了什么?