首页 > 解决方案 > 在 Bash 中找出三角形的类型

问题描述

在读取三个输入XYZ后,我有这段代码来确定三角形是等腰、不等边还是等边三角形。它的约束是:

  1. 它应该在 1 到 1000 之间
  2. 任意两条边之和应大于第三条边

除了不输出任何内容的特定数字(例如 5 和 6)外,它运行良好。

read X
read Y
read Z

if [[ $X -lt 1000 && $Y -lt 1000 && $Z -lt 1000 ]]
then 
    if [[ $X -gt 1 && $Y -gt 1 && $Z -gt 1 ]]
    then
        if [[ $((X + Y)) > $Z  &&  $((X + Z)) > $Y  &&  $((Y + Z)) > $X ]]
        then
            if [[ $X == $Y  &&  $X == $Z && $Y == $Z ]]
            then
                echo EQUILATERAL
            elif [[ $X == $Y && $X == $Z ]] || [[ $Y == $Z || $Y == $X ]] || [[ $Z == $Y || $Z == $X ]]
            then 
                echo ISOSCELES
            else
                echo SCALENE
            fi
        fi
    fi

fi

请解释为什么它没有按预期工作

标签: bash

解决方案


正如@jhnc 评论,>within[[ .. ]]运算符用于字符串比较。如果您为 x、y 和 z 输入 5,则比较测试将如下所示:

if [[ 10 > 5 ]] ...

false作为字符串比较的结果返回。请arithmetic evaluation (( .. ))改用。

那么怎么样:

read x
read y
read z

# As a first step, eliminate error cases to simplify the logic
if (( x >= 1000 || y >= 1000 || z >= 1000 || x == 0 || y == 0 || z == 0)); then
    echo "out of range"
    exit
fi

if (( x + y <= z || y + z <= x || z + x <= y )); then
    echo "not a triangle"
    exit
fi

if (( x == y && y == z )); then
    echo "equilateral"
elif (( x == y || y == z || z == x )); then
    echo "isosceles"
else
    echo "scalene"
fi

推荐阅读