greenZ

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

【shell】整数运算,小数运算

1.整数运算

【demo01】expr

typeset x=10

typeset y=2

 

n1=`expr $x + $y`

n2=`expr $x  - $y`

n3=`expr $x \* $y`  #使用expr时 符号* 需要转义

n4=`expr $x / $y`

n5=`expr $x % $y`

 

echo n1=$n1,n2=$n2,n3=$n3,n4=$n4,n5=$n5

 

【demo02】小括号

typeset x=10

typeset y=2

 

((n1=$x+$y))

((n2=$x-$y))

((n3=$x*$y))

((n4=$x/$y))

((n5=$x%$y))

 

echo n1=$n1,n2=$n2,n3=$n3,n4=$n4,n5=$n5

 

echo $(($x+$y))

echo $(($x-$y))

echo $(($x*$y))

echo $(($x/$y))

echo $(($x%$y))

 

说明:((n1=$x+$y))  等价于 n1=`expr $x + $y`

 

【demo03】中括号

typeset x=10

typeset y=2

 

echo $[$x+$y]

echo $[$x-$y]

echo $[$x*$y]

echo $[$x/$y]

echo $[$x%$y]

 

 

【demo04】let

typeset x=10

typeset y=2

 

let n1=$x+$y

let n2=$x-$y

let n3=$x*$y

let n4=$x/$y

let n5=$x%$y

 

echo n1=$n1,n2=$n2,n3=$n3,n4=$n4,n5=$n5

 

2.小数运算

【demo01】awk

#!/bin/bash

echo `awk -v x=2.45 -v y=3.123 'BEGIN{printf "%.2f\n",x*y}'`

typeset num=3.123

echo `awk -v x=2.45 -v y=$num 'BEGIN{printf "%.2f\n",x*y}'`

 

说明:awk的变量可以自定义,也可以从外部获取。

 

【demo02】|bc

#!/bin/bash

typeset n1=$(echo "scale=3; 6 / 5" | bc)

typeset n2=`echo "scale=3; 6 / 5" | bc`

 

typeset x=6

typeset y=5

typeset z=1.5

typeset n3=$(echo "scale=3;$x / $y" | bc)

typeset n4=$(echo "scale=3;$z / $y" | bc)

typeset n5=$(echo "scale=3;$x * $y" | bc)

 

echo n1=$n1,n2=$n2,n3=$n3,n4=$n4,n5=$n5

 

posted on 2019-03-13 17:02  绿Z  阅读(3992)  评论(0编辑  收藏  举报