Skip to main content

算術

let
#!/usr/bin/env bash

let NUMBER1=10
let NUMBER2=3

# Addition => + operator
let ADD=$NUMBER1+$NUMBER2
echo "Addition of two numbers : ${ADD}"

# Subtraction => - operator
let SUB=$NUMBER1-$NUMBER2
echo "Subtraction of two numbers : ${SUB}"

# Multiply => * operator
let MUL=$NUMBER1*$NUMBER2
echo "Multiply two numbers : ${MUL}"

# Divide => / operator
let DIV=$NUMBER1/$NUMBER2
echo "Division of two numbers : ${DIV}"

# Remainder => % operator
let REM=$NUMBER1%$NUMBER2
echo "Remainder of two numbers : ${REM}"

# Exponent => ** operator
let EXPO=$NUMBER1**$NUMBER2
echo "Exponent of two numbers : ${EXPO}"

# post increment and post decrement operations
let variable++
let variable--
Double Brackets

雙括號,必須是整數型態

((NUMBER2++)
((NUMBER1--))

(( NUMBER2 = NUMBER2 + 10 ))
(( NUMBER2 += 10 )) # Shorthand
expr

必須是整數型態

expr 10 + 3 # Addition
expr 10 - 3 # Subtraction
expr 10 * 3 # Multiply
expr 10 / 3 # Divide
expr 10 % 3 # Remainder
bc
# Add
$ echo "10 + 100" | bc
=> 110

$ echo "10.15 + 11.20" | bc
21.35

# Subtract
$ echo "100 - 25" | bc
=> 75

$ echo "100 - 25.5" | bc
=> 74.5

# Multiply
$ echo "10 * 5" | bc
=> 50

$ echo "10.10 * 4" | bc
=> 40.40

# without scale
echo "10.10 / 4" | bc
=> 2

# with scale
echo "scale=2;10.10 / 4" | bc
=> 2.52

$ echo "2.2^4" | bc
=> 23.4
awk
$ awk "BEGIN {print 23 * 4.5 }"
=> 103.5

$ awk "BEGIN{print int(10.111) }"
=> 10

$ awk "BEGIN{print sqrt(10) }"
=> 3.16228

# Since this is a CSV file, I am setting the field separator to(-F “,”). 
# Here the entire second column is first added and divided by the NR(number of records).
$ awk -F "," '{sum+=$2} END { print "average value from column 2 = ",sum/NR}' data.csv
Rounding 取整數
除法取整數方法 X / Y (3 / 2) = 1.5
無條件捨去 (floor rouding) X / Y , (3 / 2) = 1
無條件進位 (ceiling rouding) (X + Y – 1) / Y , (3 + 2 - 1) / 2 = 2
四捨五入 (half-up rouding) (X + Y / 2) / Y , (3 + 2 / 2) / 2 = 2
# 將 float 轉成 integer
## Way #1
float_num = 12.63333
round_num = $(printf "%.0f" $float_num)
# round_num is 12

## Way #2
float_num = 12.63333
round_num = ${float_num%%.*}
# round_num is 12

# 整數相除 3/2 後取整數值 (無條件捨去)
X=3
Y=2
echo $(( X / Y ))
# Output 1

# 整數相除 3/2 後取整數值 (四捨五入)
echo $(( (X + Y / 2) / Y ))
# Output 2