我正在嘗試撰寫代碼,提示用戶輸入 2 個數字并選擇要執行的運算子。我試圖運行它,但 if 陳述句不起作用,我不知道問題所在。
echo "Enter 1st number: "
read num1
echo "Enter 2nd number: "
read num2
echo "a. Add b. Subtract c. Multiply d. Divide"
echo "Enter Operator: "
read opr
if [[$opr==A]]
then
sum=$(($num1 $num2))
echo "The sum is $sum."
elif [[$opr==B]]
then
diff=$(($num1 - $num2))
echo "The difference is $diff"
elif [[$opr==C]]
then
prod=$(($num1 * $num2))
echo "The product is $prod"
elif [[$opr==D]]
then
quot=$(($num1 / $num2))
echo "The quotient is $quot"
else
echo "Invalid. Please enter A, B, C, and D only."
fi
uj5u.com熱心網友回復:
拋開錯誤[[不談,我建議改用case陳述句:
case $opr in
A)
sum=$(($num1 $num2))
echo "The sum is $sum."
;;
B)
diff=$(($num1 - $num2))
echo "The difference is $diff"
;;
C)
prod=$(($num1 * $num2))
echo "The product is $prod"
;;
D)
quot=$(($num1 / $num2))
echo "The quotient is $quot"
;;
*)
echo "Invalid. Please enter A, B, C, and D only."
;;
esac
uj5u.com熱心網友回復:
if您需要在所有陳述句中的雙方括號之間放置空格:
if [[ $opr == A ]]
此外:bash 是區分大小寫的,所以如果你想匹配輸入請求中的大寫和小寫字母,你應該使用這樣的東西:
if [[ ${opr^^} == A ]]
無論您鍵入什么,上面的語法都會將 $opr 變數的值轉換為大寫。
uj5u.com熱心網友回復:
我可以建議嗎
read -p "Enter 1st number: " num1
read -p "Enter 2nd number: " num2
echo -e "a. Add b. Subtract c. Multiply d. Divide" && read -p "Enter Operator: " opr
case $opr in
'a'|'A')
sum=$(($num1 $num2))
echo "The sum is $sum.";;
'b'|'B')
diff=$(($num1 - $num2))
echo "The difference is $diff";;
'c'|'C')
prod=$(($num1 * $num2))
echo "The product is $prod";;
'd'|'D')
quot=$(($num1 / $num2))
echo "The quotient is $quot";;
*)
echo "Invalid. Please enter A, B, C, and D only.";;
esac
它更清潔并達到您想要的結果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/477328.html
