【问题标题】:How do I find the middle of three numbers in shell script如何在shell脚本中找到三个数字的中间
【发布时间】:2014-10-15 11:00:40
【问题描述】:
#!/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

我遇到的问题是 or 条件。我输入了数字 1、2 和 3,但我总是得到中间数字为 1。

【问题讨论】:

    标签: bash shell command-line-arguments


    【解决方案1】:

    这个怎么样:

    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
    

    【讨论】:

    • 可以,但问题是当c为1,b为2,a为3时,中间的数字显示为1
    • @HelloMan 我修好了一点。不过,它可能会更简单。
    【解决方案2】:

    这个应该可以的:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-01
      • 2015-07-08
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 2021-08-09
      • 1970-01-01
      相关资源
      最近更新 更多