Recursive Fibonacci in Bash script

六眼飞鱼酱① 提交于 2019-11-29 12:50:25

As Wumpus said you need to produce output using for example echo. However you also need to fix the recursive invocation. The outermost operation would be an addition, that is you want:

echo $(( a + b ))

Both a and b are substitutions of fibonacci, so

echo $(( $(fibonacci x) + $(fibonacci y) ))

x and y are in turn arithmetic expressions, so each needs its own $(( )), giving:

echo $(( $(fibonacci $((first-1)) ) + $(fibonacci $((second-2)) ) ))

If you are confused by this, you should put the components into temporary variables and break down the expression into parts.

As to the actual fibonacci, it's not clear why you are passing 2 arguments.

#!/bin/bash

function fib(){
    if [ $1 -le 0 ]; then
        echo 0
    elif [ $1 -eq 1 ]; then
        echo 1
    else
        echo $[`fib $[$1-2]` + `fib $[$1 - 1]` ]
    fi

}

fib $1

The $(...) substitution operator is replaced with the output of the command. Your function doesn't produce any output, so $(...) is the empty string.

Return values of a function go into $? just like exit codes of an external command.

So you need to either produce some output (make the function echo its result instead of returning it) or use $? after each call to get the value. I'd pick the echo.

Short version, recursive

fib(){(($1<2))&&echo $1||echo $(($(fib $(($1-1)))+$(fib $(($1-2)))));}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!