使用BC进行浮点数比较

时间:2020-08-05 05:13:52

标签: bash conditional-statements

背景

这里的初学者试图学习一些Bash基础知识。

我的问题是我试图修改现有教科书示例以包括简单的输入验证。如果一个或多个输入不合适,则验证有效,但是当所有三个输入都适当时,我反而收到语法错误警告,然后给出答案。

代码已在结尾,但以下是我的想法。赞赏任何错误之处的纠正。 非常感谢。

想法

  • 我要检查三个条件。如果其中任何一个失败,将显示一条消息,程序终止。这有效。但是,如果满足所有3个条件,那么我会收到语法错误。
  • 我认为错误可能与扩展有关,因此我手动运行了命令并使用命令行提供了硬输入。例如。 bc <<< "0.5 > 0",它们似乎按预期工作。
  • 随后,似乎只有在涉及$ interest变量及其小数点时,我的问题才会出现。但是,我使用BC是因为我的理解是Bash仅使用Integers。我还错过了什么?

代码

# loan-calc: script to calculate monthly loan payments
#               formulae may be mathematically wrong, example copied from textbook
#               reference only for bash scripting, not math

PROGNAME="${0##*/}"

usage () {
    cat <<- EOF
    Usage: $PROGNAME PRINCIPAL INTEREST MONTHS

    Where:
    PRINCIPAL is the amount of the loan.
    INTEREST is the APR as a number (7% = 0.07)
    MONTHS is the length of the loan's term.

    EOF
}

read -p "Enter principal amount > " principal

read -p "Enter interest rate (E.g. 7.5% = 0.075) > " interest

read -p "Enter term length in months > " months

# Principal, interest rate, and months must be more than 0.
if (( "$principal <= 0" | bc )) || (( "$months <= 0" | bc )) || (( "$interest <= 0" | bc )); then
    usage
    exit 1
fi

result=$(bc <<- EOF
    scale = 10
    i = $interest / 12
    p = $principal
    n = $months
    p * ((i * ((1 + i) ^ n)) / (((1 + i) ^ n) - 1))
EOF
)

printf "%0.2f\n" $result

1 个答案:

答案 0 :(得分:0)

Shell Arithmetic

(( 1 | bc ))不会将1传送到bc中。在(( expression ))内计算表达式时,|是按位OR运算符, 不是管道

{(( bc ))每次取值为1,因此您所有的条件测试都只是将数字与1进行“或”运算,不是将数字输入bc

您在括号内的表达式应该是使用管道将数学字符串回显到bc中的输出,例如(( $(echo "$variable <= 0"| bc) ))

这可以包装在一个命名函数中,这样if语句就更具可读性。

notValid() {
    (( $(echo "$1 <= 0" | bc) ))
}

# Principal, interest rate, and months must be more than 0.
if  notValid "$principal" || notValid "$months" || notValid "$interest"; then
    usage
    exit 1
fi