【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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM