shell腳本,通過傳參求斐波那契數列如(0,1,1,2,3,5,8,13..........)


[root@localhost wyb]# cat fibo.sh 
#!/bin/bash

#斐波那契數列 0,1,1,2,3,5,8,13

echo 0 > file
echo 1 >> file

count=$1

for i in `seq $count`
do
first=$(tail -2 file |head -1)
two=$(tail -1 file)
echo $((first+two)) >> file
done
cat file
[root@localhost wyb]# bash fibo.sh 10
0
1
1
2
3
5
8
13
21
34
55
89
[root@localhost wyb]# bash fibo.sh 7
0
1
1
2
3
5
8
13
21
[root@localhost wyb]# 
第二種方法,通過間接賦值來來傳。用到read -p

[root@localhost wyb]# cat 2fibo.sh #!/bin/bash #斐波那契數列 0,1,1,2,3,5,8,13 echo 0 > file echo 1 >> file #count=$1 read -p "Please Input a number:" count for i in `seq $count` do first=$(tail -2 file |head -1) two=$(tail -1 file) echo $((first+two)) >> file done cat file [root@localhost wyb]# bash 2fibo.sh Please Input a number:4 0 1 1 2 3 5 [root@localhost wyb]# bash 2fibo.sh Please Input a number:6 0 1 1 2 3 5 8 13 [root@localhost wyb]# bash 2fibo.sh Please Input a number:20 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 [root@localhost wyb]#
 
         

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM