Bash脚本-斐波那契 [英] Bash Script - Fibonacci
问题描述
我试图制作一个可以计算输入数字的斐波那契的递归函数,以这种方式卡住我如何获取通过递归获得的值.
I was trying to make a recursive function that can calculate the Fibonacci of the enter number, by the way I got stuck on how to get the values obtained by the recursion.
#!/bin/bash
#Function - Fibonacci
fib()
{
number=$1
if (( number < 2 ))
then
(( tmp = number ))
else
((--number))
term1=$(fib $number)
((--number))
term2=$(fib $number)
(( tmp = $(( term1 + term2 )) )) #Problem is here
fi
(( result = $result + tmp ))
return $result
}
#Main Program.
fib $1
echo fib $1 = $?
有人可以帮助我吗?
推荐答案
您的代码有两个问题.您不能使用$?
进行任何有用的算术运算,因为数字会在255处回绕.并且嵌入的$((...))
根本没有用,因为您已经在双括号内的算术上下文中.
There are a couple of issues with your code. You cannot use $?
for any useful arithmetic because the number wraps around at 255. And the embedded $((...))
is not useful at all -- you are already in arithmetic context inside the double parentheses.
#!/bin/bash
fib()
{
local number term1 term2 # Avoid leaking to main scope
number=$1
if ((number < 2))
then
((tmp=number))
else
((--number))
term1=$(fib "$number")
((--number))
term2=$(fib "$number")
((tmp=term1+term2))
fi
((result=result+tmp))
printf '%s\n' "$result"
}
#Main Program.
fib "$1" # Quote argument properly!
在((
算术括号))
中,您不需要在变量前面使用$
;这是无害的,但您应该尝试保持一致.
Inside the ((
arithmetic parentheses ))
you don't need the $
in front of variables; it's harmless, but you should probably try to be consistent.
与任何幼稚的Fibonacci实现一样,这是非常低效的.在辅助函数中一次计算序列的开头,然后拉出最终结果并显示它会更聪明.
As with any naïve Fibonacci implementation, this is hugely inefficient. It would be smarter to calculate the head of the sequence once in a helper function, then pull the final result and display it.
#!/bin/bash
fib2() {
local f
((f=$1+$2))
printf '%i %i\n' "$f" "$1"
}
fib()
{
local i j
j=$1
shift
for((i=1; i<j; ++i)); do
set -- $(fib2 ${1-1} ${2-0})
done
printf '%s\n' "${1-$i}"
}
#Main Program.
fib "$1"
这篇关于Bash脚本-斐波那契的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!