Recursive function in bash

后端 未结 6 1660
渐次进展
渐次进展 2020-12-13 09:33

I want to do a function that will return the factorial of a number in bash

Here\'s the current code that doesn\'t work, can anyone tell me what\'s wrong and how to c

6条回答
  •  误落风尘
    2020-12-13 10:27

    clear cat
    
    fact()
    
    {
    
            i=$1
            if [ $i -eq 0 -o $i -eq 1 ]
            then
                    echo 1
            else
                    f=`expr $i \- 1`
                    f=$(fact $f)
                    f=`expr $i \* $f`
                    echo $f
            fi
    }
    
    read -p "Enter the number : " n
    
    if [ $n -lt 0 ]
    
    then
    
            echo "ERROR"
    
    else
    
            echo "THE FACTORIAL OF $n : $(fact $n) "
    fi
    

提交回复
热议问题