您的位置:首页 > 运维架构 > Shell

shell实例(十九) ---nl,bc命令

2011-03-17 20:15 204 查看
1.一个计算自己行号的脚本

#! /bin/sh
nl `basename $0`
cat -n `basename $0`
exit 0

2.按月偿还贷款

#! /bin/sh
echo
echo "Given the principal, interset rate, and term of a mortgage,"
echo "Calculate the monthly payment."

bottom=1.0
echo

echo -n "Enter principal (no commas) "
read principal
echo -n "Enter interset rate (percent) "
read interest_r
echo -n "Enter term (months) "
read term

interest_r=$(echo "scale=9; $interest_r/100.0" | bc) -----------scale=9定义小数点位数为9位
interest_rate=$(echo "scale=9; $interest_r/12 + 1.0" | bc)
top=$(echo "scale=9; $principal*$interest_rate^$term" | bc)
echo;echo "Please be patient. This may take a while."
let "months = $term - 1"
for ((x=$months; x>0; x--))
do
bot=$(echo "scale=9; $interest_rate^$x" | bc)
bottom=$(echo "scale=9; $bottom+$bot" | bc)
done
echo "scale=2; $top/$bottom" | bc
payment=$(echo "scale=2; $top/$bottom" | bc)
echo
echo "monthly payment = /$$payment"
echo

exit 0

3.使用"here document“来调用bc

#! /bin/sh
var1=`bc << EOF
18.33 * 19.78
EOF`

echo $var1

v1=23.53
v2=17.881
v3=83.501
v4=171.63

var2=$(bc << EOF
scale=4
a = ( $v1 + $v2 )
b = ( $v3 + $v4 )
a * b + 15.35
EOF
)

echo $var2

var3=$(bc -l << EOF
scale=9
s ( 1.7 )
EOF
)

echo $var3
hyp=
hypotenue ()
{
hyp=$(bc -l << EOF
scale=9
sqrt ( $1 * $1 + $2 * $2 )
EOF
)
}
hypotenue 3.68 7.31
echo "hypotenuse = $hyp"

exit 0

4.计算圆周率

! /bin/sh
DIMENSION=1000
MAXSHOTS=1000
PMULTIPLIER=4.0
get_random () {
SEED=$(head -1 /dev/urandom | od -N 1 | awk '{ print $2 }')
RANDOM=$SEED
let "rnum = $RANDOM % $DIMENSION"
echo $rnum
}

distance=
hypotenuse () {
distance=$(bc -l << EOF
scale=0

sqrt ( $1 * $1 + $2 * $2 )
EOF
)
}

shots=0
splashes=0
thuds=0
pi=0

while [ "$shots" -lt "$MAXSHOTS" ]
do
xCoord=$(get_random)
yCoord=$(get_random)
hypotenuse $xCoord $yCoord
((shots++))
printf "#%4d " $shots
printf "Xc = %4d " $xCoord
printf "Yc = %4d " $yCoord
printf "Distance = %5d " $distance

if [ "$distance" -le "$DIMENSION" ]
then
echo -n "THUD! "
((thuds++))
fi

pi=$(echo "scale=9; $PMULTIPLIER*$splashes/$shots" | bc)
echo -n "pi ~ $pi"
echo
done

echo
echo "After $shots shots ,PI looks like approximately $pi."
echo
exit 0

5.计算直角三角形的斜边

#! /bin/sh
ARGS=2
E_BADARGS=65

if [ $# -ne "$ARGS" ]
then
echo "Usage: `basename $0` side_1 side_2"
exit $E_BADARGS
fi

AWKSCRIPT=' {print( "%3.7f/n", sqrt($1*$1 + $2*$2) ) } ' -----长度7位,整数占3位
echo -n "Hypotenuse of $1 and $2 = "
echo $1 $2 | awk "$AWKSCRIPT"
exit 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: