您的位置:首页 > 运维架构 > Shell

用shell脚本语言实现一个斐波那契数列的递归和非递归版本

2017-07-08 00:57 363 查看
代码:

#!/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



结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  脚本语言 递归 函数