• 【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 ",x*y}'`

    typeset num=3.123

    echo `awk -v x=2.45 -v y=$num 'BEGIN{printf "%.2f ",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

  • 相关阅读:
    观光公交
    luogu 4779 【模板】
    最小生成树(luogu 3366)
    计算系数
    更新区间,求单点—— luogu 3368
    HDU
    HDU
    HDU
    HDU
    BFS
  • 原文地址:https://www.cnblogs.com/greenZ/p/10524361.html
Copyright © 2020-2023  润新知