Bash脚本中的递归斐波那契 [英] Recursive Fibonacci in Bash script

查看:49
本文介绍了Bash脚本中的递归斐波那契的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的尝试:

#!/bin/bash

function fibonacci(){

first=$1
second=$2

if (( first <= second ))
then
return 1

else 

return $(fibonacci $((first-1)) ) + $(fibonacci $((second-2)) )
fi
}

echo $(fibonacci 2 0)

我认为我在else语句上遇到麻烦.我收到错误 return:+:需要数字参数在第14行.

I think i'm having trouble with the else statement. I get the error return: +: numeric argument required on line 14.

我遇到的另一个问题是,即使我执行 echo $(fibonacci 0 2),脚本也不会显示任何数字.我以为它将显示为1,因为在这种情况下我要返回1.有人可以给我一些有关如何完成此操作的提示吗?

The other problem that i'm having is that the script doesn't display any numbers even if i do echo $(fibonacci 0 2). I thought it would display a 1 since i'm returning a 1 in that case. Can someone give me a couple of tips on how to accomplish this?

检查出您的一些答案后,这是我的第二次尝试.它可以正常工作,只是它以1 + 1 + 1 + 1等形式显示第n个斐波那契数.为什么?

After checking out some of your answers this is my second attempt.. It works correctly except that it displays the nth fibonacci number in the form 1+1+1+1 etc. Any ideas why?

#!/bin/bash

function fibonacci(){

first=$1
second=$2

if (( first <= second ))
then
echo 1


else 

echo $(fibonacci $((first-1)) ) + $(fibonacci $((first-2)) )
fi
}

val=$(fibonacci 3 0)
echo $val

我最后的尝试:

#!/bin/bash

function fibonacci(){

first=$1

if (( first <= 0 ))
then
echo 1


else 

echo $(( $(fibonacci $((first-1)) ) + $(fibonacci $((first-2)) ) ))
fi
}

val=$(fibonacci 5)
echo $val

感谢帅哥.

推荐答案

正如Wumpus所说,您需要使用例如 echo 产生输出.但是,您还需要修复递归调用.最外层的操作是一个附加操作,这是您想要的:

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 ))

a b 都是 fibonacci 的替代,所以

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

x 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.

对于实际的斐波那契,还不清楚为什么要传递2个参数.

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

这篇关于Bash脚本中的递归斐波那契的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆