#!/bin/bash
#echo "1.$12.$23.$3"
if [ "$2" == "+" ]
then
RES=`expr $1 + $3`
echo ">>the result is:$RES"
elif [ "$2" == "-" ]
then
RES=`expr $1 - $3`
echo ">>the result is:$RES"
#這裡說明下,之所以不用“*”而用“x”,
#是因為在命令列輸入*,shell解析用問題,
#*不能以參數的形式傳遞給指令碼,所以就用x代替了,
#這樣能規避這個問題,但是我仍然不知道*在命令列不能傳遞給指令碼,
#那位大俠能幫忙解釋下,非常感謝~ elif [ "$2" == "x" ]
then
RES=`expr $1 \* $3`
echo ">>the result is:$RES"
elif [ "$2" == "%" ]
then
if [ "$3" == "0" ] ##判斷除數是否為0
then
echo "input error,division by 0"
exit
fi
BIG=`expr $1 / $3` ##取整
SMALL=`expr $1 % $3` ##取餘
LONG=6 ##小數點後保留的位元
COUNT=0 ##迴圈的計數器,要小於LONG
RES1=0 ##
##無限迴圈,目的是如果SMALL不為零,說明沒有整除,計算餘數的方法就是
##在SMALL後加上LONG個0,除以除數取整就可以了,LONG是小數點後精確的位元
while :
do
SMALL=`expr $SMALL \* 10`
COUNT=`expr $COUNT + 1`
if [ $COUNT == $LONG ]
then
break
fi
done
RES1=`expr $SMALL / $3` ##到此餘數就計算好了
echo ">>The result is:$BIG.$RES1" ##把整數部分和餘數部分拼接起來輸出就是結果了
elif [ "$1" == "--help" ]
then
echo "input format:"
echo "calculator.sh x + y"
echo "calculator.sh x - y"
echo "calculator.sh x x y"
echo "calculator.sh x % y"
echo "calculator.sh --help"
else
echo "input format error!"
fi