Shell实现斐波那契数列计算

斐波那契数计算器 (numberempire.com)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/bin/bash

fibonacci() {
n=$1
if [ $n -eq 0 ]; then
echo 0
elif [ $n -eq 1 ]; then
echo 1
else
a=0
b=1
i=2
while [ $i -le $n ]; do
c=$((a + b))
a=$b
b=$c
i=$((i + 1))
done
echo $b
fi
}

read -p "请输入N值(N < 50): " N

if [ $N -ge 0 ] && [ $N -lt 50 ]; then
result=$(fibonacci $N)
echo "斐波那契数列的第 $N 项为: $result"
else
echo "输入的N值不在有效范围内!"
fi

https://github.com/zznn-cloud/zznn-cloud-blog-images/raw/main/Qexo/24/3/image_caa7837e83fa0efebe83bac133122bd4.png

https://github.com/zznn-cloud/zznn-cloud-blog-images/raw/main/Qexo/24/3/image_e9d599e5ba7c00c4a861753f0f01a4cb.png