第三章:Creating Utilities--29.计算贷款

   目的就是在温度转换上再进一步的了解数学计算。 shell

代码: rest

#!/bin/sh

# loancalc.sh -- 指定贷款的本金、税率、年限

# 公式: M = P * (J / (1- (1 + J)** - N))
# 其中, P = 本金、J = 每个月税率、N = 年限(月表示)
# 用户输入P、I(年利率)、L(长度,年份)

# 注意,公式中后面的 (1 + J)** - N 是一个总体,表示指数
# 好比,(1 + 1)** - 2 就是 2 ^ -2,至关于 1/2*2 = 0.25

#source library.sh

if [ $# -ne 3 ]; then
	echo "Usage: `basename $0` principal interest loan-duration-years" >&2
	exit 1
fi

# 这儿用到的scriptbc.sh是第九个脚本的程序
# 传给它的参数是一个公式,部分运算符号须要转义
# 转义的有: ( ) * ^
P=$1 I=$2 L=$3
J="$(scriptbc.sh -p 8 $I/\(12 \* 100\))"
N="$(($L*12))"
M="$(scriptbc.sh -p 8 $P\*\($J/\(1-\(1+$J\)\^-$N\)\))"

dollars="$(echo $M | cut -d. -f1)"
cents="$(echo $M | cut -d. -f2 | cut -c1-2)"

# newnicenum.sh是第4个脚本中的程序
cat << EOF
A $L year loan at $I% interest with a principal amount of $(newnicenum.sh $P 1)
results in a payment of \$$dollars.$cents each month for the duration of
the loan($N payments).
EOF

exit 0
运行结果:

$ loancalc 40000 6.75 4 
A 4 year loan at 6.75% interest with a principal amount of 40,000 
results in a payment of $953.21 each month for the duration of 
the loan (48 payments). 

$ loancalc 40000 6.75 5 
A 5 year loan at 6.75% interest with a principal amount of 40,000 
results in a payment of $787.33 each month for the duration of 
the loan (60 payments).
分析脚本:
这个脚本比较完整的展现了一个数学公式的运算。

ps: 

   原书中在脚本分析这一块还有一些阐述,不过我以为用处不大。最重要的就是给scriptbc.sh脚本传递数学公式,这个掌握了,这个脚本就没问题了。其它的,好比提示用户具体参数含义,以及每一个参数的格式之类的都是次要的。
   另外,原书中还分析了cut的两个命令,由于在以前的第6个脚本中,重点介绍过了,就再也不重复了。
code

相关文章
相关标签/搜索