Script calculator division

2019-07-29 11:53发布

问题:

i have a problem with my syntax below, i want to output the division of two numbers in decimal,but if i input 4 and 5, my output is 0 not 0.8 when i divide all others work fine.

case $ch in
  1)sum=`expr $n1 + $n2`
   echo "Sum ="$sum;;
  2)sum=`expr $n1 - $n2`
    echo "Sub = "$sum;;
  3)sum=`expr $n1 \* $n2`
    echo "Mul = "$sum;;
  4)sum=`expr $n1 / $n2`
    echo "Div = "$sum;;
  *)echo "Invalid choice";;
esac

回答1:

Expr only implements integer arithmetic. Look into using something else, like dc.



回答2:

Use bc.

sum=`echo -e "scale=5\n$n1/$n2" | bc`

Your division will give 0.8 with this.



标签: bash shell logic