如何在shell脚本中找到三个数字的中间位置

时间:2014-10-14 22:46:36

标签: bash shell command-line-arguments

#!/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。

2 个答案:

答案 0 :(得分: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

答案 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