【问题标题】:shell script zins calculationshell脚本zins计算
【发布时间】:2016-12-06 13:21:18
【问题描述】:

我需要一个计算基本税的 bash 脚本。 它应该可以由

调用

tax.sh 或带有可选参数:tax.sh(资本或帮助)(利率)(持续时间)

我所拥有的是:

re='^-?[0-9]+([.][0-9]+)?$'
echo "capital: "
read capital
if ![[ $capital =~ $re ]] ; then
  echo "invalid capital!" >&2; exit 1
fi
echo "rate: "
    read rate
    if ![[ $rate=~ $re ]] ; then
      echo "invalid rate!" >&2; exit 1
    fi
echo "duration: "
    read duration
    if ![[ $duration=~ $re ]] ; then
      echo "invalid duration!" >&2; exit 1
    fi
echo "the capital after "$duration" years is: "
echo "scale=5;($capital*($rate/100)*$duration)+$capital" | bc

我不知道如何实现参数或正确计算:/ 计算总是比它应该的小一点。

【问题讨论】:

  • 您的问题是什么?您的脚本似乎没问题,除了少数语法错误实例在 ![[ $rate=~ $re ]] ;! [[ $rate =~ $re ]] ; 中留下空格
  • “计算总是比它应该的小一点。”。例子?
  • 例如5000 1 5 应该是 5255.05 但在 shell 脚本中是 5250。第二个问题是我如何实现参数
  • @DimitriStrogatrov:$tax 变量在计算中做了什么?之前没有被读取或设置过?
  • 抱歉,这实际上是我的打字错误...我的意思是 $rate 那里。从腻子复制时发生...

标签: bash shell parameters tax


【解决方案1】:

如何实现参数

一种方法是将positional parameters 分配给您的变量,如果parameter 不为空,则跳过每个变量的read; e. g.

capital=$1; ${capital:+:} read -p "capital: " capital
…
rate=$2; ${rate:+:} read -p "rate: " rate
…
duration=$3; ${duration:+:} read -p "duration: " duration
…

正确计算

正如 pjh 正确地写道:“答案太小的原因是因为公式假设单利但需要复利。必须使用不同的公式。”这是:

echo "scale=5;$capital*(1+$rate/100)^$duration" | bc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-01
    • 2023-03-05
    • 1970-01-01
    • 2012-10-21
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多