linxu shell 递归和while循环 的 factorial计算

linxu shell 递归和while循环 的 factorial计算

1
2
3
4
5
6
7
8
9
1 #!/bin/bash
2 read -p "Enter a number: " num
3 result=$num
4 while [ $num -gt 1 ]
5 do
6 num=$[ $num - 1 ]
7 result=$[ $result * $num ]
8 done
9 echo "The result is $result"

1
2
3
4
5
6
7
8
9
10
11
12
13
 1 #!/bin/bash
2 function factorial {
3 if [ $1 -le 0 ];then
4 echo 1
5 else
6 local temp=$[ $1 -1 ]
7 local result=`factorial $temp`
8 echo $[ $result * $1 ]
9 fi
10 }
11 read -p "请输入要计算的数字: " num
12 result=`factorial $num`
13 echo -e "结果为$result\n"