使用if語句
#!/bin/bash
# 這是乙個計算器
read -t 30 -p "please input the first number: " num1
read -t 30 -p "please input the second number: " num2
read -t 30 -p "please input the second operator(\"+\", \"-\", \"*\", \"/\"): "
opif
[ -n "$num1" -a -n "$num2" -a -n "$op"
]then
# 1.校驗兩個運算元必須為數值
test1=
$(echo $num1 |
sed's/[0-9]//g'
) test2=
$(echo $num2 |
sed's/[0-9]//g'
) if
[ -n "$test1" -o -n "$test2"
]then
echo
"please input number."
exit 1
fi# 2.判斷操作符是否正確if[
"$op"
=="+"
]then
result=
$(($num1 + $num2))
elif
["$op"
=="-"
]then
result=
$(($num1 - $num2))
elif
["$op"
=="*"
]then
result=
$(($num1 * $num2))
elif
["$op"
=="/"
]then
result=
$(($num1 / $num2))
else
echo
"please input correct operator, like \"+\", \"-\", \"*\", \"/\"."
exit 2
fi# 3.列印結果
echo
"$num1
$op$num2 = $result"
exit 0
else
echo
"number and oprator must not be empty"
exit 3
fi
使用case語句
#!/bin/bash
# 這是乙個計算器
read -t 30 -p "please input the first number: " num1
read -t 30 -p "please input the second number: " num2
read -t 30 -p "please input the second operator(\"+\", \"-\", \"*\", \"/\"): "
opif
[ -n "$num1" -a -n "$num2" -a -n "$op"
]then
# 1.校驗兩個運算元必須為數值
test1=
$(echo $num1 |
sed's/[0-9]//g'
) test2=
$(echo $num2 |
sed's/[0-9]//g'
) if
[ -n "$test1" -o -n "$test2"
]then
echo
"please input number."
exit 1
fi# 2.判斷操作符是否正確
case
$opin
"+")
result=
$(($num1 + $num2))
;;"-"
) result=
$(($num1 - $num2))
;;"*"
) result=
$(($num1 * $num2))
;;"/"
) result=
$(($num1 / $num2))
;; *)
echo
"please input correct operator, like \"+\", \"-\", \"*\", \"/\"."
exit 2
;; esac
# 3.列印結果
echo
"$num1
$op$num2 = $result"
exit 0
else
echo
"number and oprator must not be empty"
exit 3
fi
shell數值計算(加減乘除)
shell 包含三個命令 bc expr let可用於數值計算。輸入 整數,let和expr都無法進行浮點運算,但是bc和awk可以。輸出 bc expr可直接顯示計算結果 let則丟棄計算結果,可通過傳遞結果到變數,取變數值獲得計算結果。格式示例 bc root localhost echo 30...
BigDecimal加減乘除計算
bigdecimal num1 new bigdecimal 0.005 bigdecimal num2 new bigdecimal 1000000 bigdecimal num3 new bigdecimal 1000000 盡量用字串的形式初始化 bigdecimal num12 new bi...
計算機實現加減乘除
計算機是怎麼操作的!0000 0100 0000 0101 加法 計算機是不會直接加的 0000 1001 計算機的實現原理 第一步 異或運算 不一樣等於1 0000 0100 0000 0101 0000 0001 第二步 與運算 都是1等於1 目的是判斷是否有進製,如果與運算結果為0,則沒有進製...