2014-10-14 1 views
-1
#!/bin/bash 

echo "Enter three numbers and this program will give you the middle number : " ; read num1 ; read num2 ; read num3 

if [ "$num1" -gt "$num2" ] && [ "$num1" -lt "$num3" ] || [ "$num1" -lt "$num2" ] && [ "$num1" -gt "$num3" ]; then 
{ 
echo "The middle number is $num1" 
} 

elif [ "$num2" -gt "$num1" ] && [ "$num2" -lt "$num3" ] || [ "$num2" -lt "$num1" ] && [ "$num2" -gt "$num3" ]; then 
{ 
echo "The middle number is $num2" 
} 

elif [ "$num3" -gt "$num1" ] && [ "$num3" -lt "$num2" ] || [ "$num3 -lt "$num1" ] && [ "$num3" -gt "$num2" ]; then 
{ echo "The middle number is $num3" } 

fi 

문제는 또는 조건과 관련이 있습니다. 나는 1, 2, 3 번을 입력하지만, 중간 숫자는 항상 1로한다.셸 스크립트에서 세 숫자의 중간을 찾으려면 어떻게합니까?

답변

0

을 :

getmid() { 
    if (($1 <= $2)); then 
    (($1 >= $3)) && { echo $1; return; } 
    (($2 <= $3)) && { echo $2; return; } 
    fi; 
    if (($1 >= $2)); then 
    (($1 <= $3)) && { echo $1; return; } 
    (($2 >= $3)) && { echo $2; return; } 
    fi; 
    echo $3; 
} 

# All permutations of 1, 2 and 3 print 2. 
getmid 1 2 3 
getmid 2 1 3 
getmid 1 3 2 
getmid 3 1 2 
getmid 2 3 1 
getmid 3 2 1 
+0

작동 감사합니다,하지만 문제는 C가 1 인 경우이다, b는 2이고 a는 3입니다. 중간 숫자는 1로 나타납니다. –

+0

저는 그것을 조금 비틀었고 고마워했습니다! –

+0

@HelloMan 나는 그것을 조금 고쳤다. 아마도 더 간단 할 수 있습니다. – ooga

1

이 하나가 작동합니다 :이 방법에 대해

#!/bin/bash 

echo "Enter three numbers and this program will give you the middle number : " ; read num1 ; read num2 ; read num3; 

if [ "$num1" -gt "$num2" ] && [ "$num1" -lt "$num3" ]; then 
{ 
echo "The middle number is" $num1 ; 
} 

elif [ "$num1" -lt "$num2" ] && [ "$num1" -gt "$num3" ]; then 
{ 
echo "The middle number is" $num1 ; 
} 

elif [ "$num2" -gt "$num1" ] && [ "$num2" -lt "$num3" ]; then 
{ 
echo "The middle number is" $num2 ; 
} 
elif [ "$num2" -lt "$num1" ] && [ "$num2" -gt "$num3" ]; then 
{ 
echo "The middle number is" $num2 ; 
} 

elif [ "$num3" -gt "$num1" ] && [ "$num3" -lt "$num2" ]; then 
{ 
echo "The middle number is" $num3 ; 
} 
elif [ "$num3" -lt "$num1" ] && [ "$num3" -gt "$num2" ]; then 
{ 
echo "The middle number is" $num3 ; 
} 

fi 
+0

그것은 작동하지 않습니다 –

+0

가 IT 작동 –

관련 문제