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

【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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值