递归的linux斐波纳契bash脚本 [英] recursive fibonacci linux bash script

查看:125
本文介绍了递归的linux斐波纳契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语句的麻烦。我得到的错误收益:+:需要数字参数
在线14

这是我遇到的另一个问题是,该脚本不显示任何号码,即使我做回声$(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等任何想法,为什么?

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

我的最后一次尝试:

My final attempt:

#!/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说你需要使用例如回声产生输出。
然而,你还需要修复的递归调用。
最外层的操作将是一个加法,这是你想要的:

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 斐波纳契的换人 ,所以

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

X 是反过来算术前pressions,因此需要其各自的 $(()),赠送:

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

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

如果你被这种困惑,你应该把组件集成到临时变量,并打破前pression成几部分。

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.

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

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