Chinaunix首页 | 论坛 | 博客
  • 博客访问: 465730
  • 博文数量: 93
  • 博客积分: 5006
  • 博客等级: 上校
  • 技术积分: 1002
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-30 13:58
文章分类

全部博文(93)

文章存档

2012年(2)

2011年(68)

2010年(23)

分类: Python/Ruby

2011-08-11 21:47:56

bash函数可以呼叫自己本身,称为递归函数

下面一个小例子明白递归的使用
求一个数的阶层
  1 #! /bin/bash
  2
  3 #练习如何使用递归函数
  4 #Auter:panda
  5 #Time:2011-08-10
  6 #函数的用途是计算阶乘
  7                                                                                                                                  
  8 function factor_in ()
  9 {
 10     local tmp
 11     local tmp1
 12 #tmp记录传入函数的整数值
 13     tmp="$1"
 14 #如果传入的值是1,则不用计算,结果直接为1
 15     if [ $tmp -eq 1 ] ; then
 16         echo -n " 1 "
 17         r=1
 18     else
 19 #如果传入的值不是1
 20     echo -n  " $tmp * "
 21 #tmp暂时存在tmp1里
 22     tmp1=$tmp
 23     tmp=$(($tmp-1))
 24 #递归调用该函数
 25     factor_in $tmp
 26     r=$(($tmp1*$r))
 27         fi
 28 }

运行结果:
panda@panda-pc:~/Code/Shell$ ./recursive.sh
使用法: ./recursive.sh 正整数
panda@panda-pc:~/Code/Shell$ ./recursive.sh  5

5! =  5 *  4 *  3 *  2 *  1 = 120
panda@panda-pc:~/Code/Shell$

阅读(5012) | 评论(3) | 转发(1) |
给主人留下些什么吧!~~

随1意2o2011-08-21 10:52:23

sunjiangang-ok: auther错了,应该是author.....
嗯  我一直那么写的   被你发现了  你真牛

sunjiangang-ok2011-08-21 08:09:50

auther错了,应该是author

sunjiangang-ok2011-08-21 08:08:59

auther错了,应该是author