我正在準備用于比較 3 個數字的 shell 代碼。我的代碼如下
#!/bin/bash
echo "enter any 3 numbers"
read num1
read num2
read num3
if [ $num1 -gt $num2 ]
then
if [ $num1 -gt $num3 ]
then
echo "$num3 is greater than $num1 & $num1"
fi
elif [ $num2 -gt $num1 ]
then
if [ $num2 -gt $num3 ]
then
echo "$num2 is greater than $num1 & $num3"
fi
elif [ $num3 -gt $num1 ]
then
if [ $num3 -gt $num2 ]
then
echo "$num3 is greater then $num2 &$num1"
fi
else
echo "invalid"
fi
如果我輸入第一個或第二個最高數字,那么它會給出正確的輸出,但如果我輸入第三個最高數字,則不會進行評估。第二個 elif 陳述句沒有得到評估。
uj5u.com熱心網友回復:
讓我們先讓它更具可讀性:
if [ $num1 -gt $num2 ]; then
if [ $num1 -gt $num3 ]; then
echo "$num1 is greater than $num2 & $num3" # typos fixed
fi
elif [ $num2 -gt $num1 ]; then
if [ $num2 -gt $num3 ]; then
echo "$num2 is greater than $num1 & $num3"
fi
elif [ $num3 -gt $num1 ]; then
if [ $num3 -gt $num2 ]; then
echo "$num3 is greater then $num1 & $num2" # typos fixed
fi
else
echo "invalid"
fi
如果您輸入 eg num1 == 1, num2 == 2, num3 == 3,那么它將不起作用,因為這是真的:
elif [ $num2 -gt $num1 ]; then
但在那之后,這是錯誤的:
if [ $num2 -gt $num3 ]; then
因此沒有輸出。如果那是您所期望的,則不會繼續執行elif [ $num3 -gt $num1 ]; then,如果不是那樣作業。
你可以像這樣重構它:
if [ $num1 -gt $num2 ] && [ $num1 -gt $num3 ]; then
echo "$num1 is greater than $num2 & $num3"
elif ...
并繼續添加elifs 直到涵蓋所有可能的排列和情況。
uj5u.com熱心網友回復:
如果您一次進行兩個比較,這會簡單得多:
if [ "$num1" -gt "$num2" ] && [ "$num1" -gt "$num3" ]; then
echo "$num1 is greater than $num2 and $num3"
elif [ "$num2" -gt "$num1" ] && [ "$num2" -gt "$num3" ]; then
echo "$num2 is greater than $num1 and $num3"
elif [ "$num3" -gt "$num1" ] && [ "$num3" -gt "$num2" ]; then
echo "$num3 is greater than $num1 and $num2"
# else echo "no one number is biggest"
fi
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/341831.html
上一篇:運行os.system()時python意外的EOF
下一篇:Shell-回圈處理檔案
