代碼:
#!/bin/bash -x
#第一種寫法
#first=1
#second=1
#last=1
#
#if [ $1 -le 2 ];then
# echo 1
#fi
#
#i=3
#while [ $i -le $1 ]
#do
# let last=first+second
# let first=second
# let second=last
# let i++
#done
#
#echo $last
#
#第二個版本 用數組
#array[0]=1
#array[1]=1
#
#read num
#i=2
#while [ $i -lt $num ]
#do
# let array[$i]=array[$i-1]+array[$i-2]
# let i++
#done
#
#echo ${array[$num-1]}
#第三種遞歸寫法
function fib()
{
temp=$1
if [ $temp -le 2 ];then
echo 1
return
fi
res1=`fib $(( temp-1 ))` #將temp減1的值當做fib 的參數,求出這個函數的返回值給res1
res2=`fib $(( temp-2 ))`
echo $((res1+res2)) #輸出res1+rest2後的值。
}
read num
fib $num
結果: