简体   繁体   English

Linux Shell Scripting 递归求幂

[英]Linux Shell Scripting recursive exponentation

I am writing a script that takes 2 numbers as an input and uses recursion to power on number to the power of the other, simple exponentiation.我正在编写一个脚本,该脚本将 2 个数字作为输入,并使用递归将数字设置为另一个简单幂的幂。 However I am new to scripting and cannot figure out where my syntax is errored here.但是,我是脚本编写新手,无法弄清楚这里的语法错误在哪里。

Here is the script这是脚本

#!/bin/bash
echo "Enter number: "
read number
echo "Enter power: "
read power

echo "Powering $number to power of $power!" 

exp () {

    if [ $2 = 1 ]
    then
        return $1
    fi

    return $1 * $(exp $1 $2-1 )

}

result=$(exp $number, $power)

echo "Result: $result"

Currently, it kind of freezes, im not sure if I use the parameters correctly (in terms of syntax).目前,它有点冻结,我不确定我是否正确使用了参数(就语法而言)。

You need $(( )) to force arithmetic evaluation.您需要$(( ))来强制算术评估。 Then you can do it with return values:然后你可以用返回值来做到这一点:

number=2 power=7
exp () {
    if [ $2 -eq 1 ]; then return $1; fi
    exp $1 $(($2-1))
    return $(($1 * $?))
}
exp $number $power; result=$?
echo "Result: $result"

but it's a bad idea, because shells kind of reserve nonzero return values to communicate failure (eg the above solution will "break" set -e ).但这是一个坏主意,因为 shell 会保留非零返回值来传达失败(例如,上述解决方案将“破坏” set -e )。

More idiomatically, you can use stdout:更惯用的是,您可以使用标准输出:

set -e
number=2 power=7
exp () {
    if [ $2 -eq 1 ]; then echo $1; return; fi
    echo $(($1 * $(exp $1 $(($2-1)) ) ))
}
result=$(exp $number $power)
echo "Result: $result"

but that's kind of inefficient with all the subshells.但这对于所有子外壳来说都是低效的。 Best to avoid the recursion and simply loop:最好避免递归并简单地循环:

number=2 power=7
exp () {
    local res=1 i=0;
    while [ $i -lt $2 ]; do res=$((res*$1)); i=$((i+1)); done
    echo $res
}
exp $number $power

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM