bash - 在 Bash 中找出三角形的类型
问题描述
在读取三个输入X、Y和Z后,我有这段代码来确定三角形是等腰、不等边还是等边三角形。它的约束是:
- 它应该在 1 到 1000 之间
- 任意两条边之和应大于第三条边
除了不输出任何内容的特定数字(例如 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
请解释为什么它没有按预期工作
解决方案
正如@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
推荐阅读
- python-3.x - 使用 boto3 返回 s3 前缀中的对象列表
- image - 在帐户页面上显示 Woocommerce 订单图像
- javascript - 如何使用 Playwright 与 Google Maps 或 OpenStreetMaps 等地图进行交互?
- python - 将个人访问令牌输送到 az devops login for windows cmd
- javascript - 赛普拉斯测试:如何保留 access_token/cookies/sessions?
- javascript - JS正则表达式匹配括号之间的数字
- python - 一次绘制整个数据框时,如何在 Jupyter Notebook 上的线图中更改单条线的颜色和线型?
- node.js - Express 节点和 Passport 登录/注销/Cookie 问题
- r - 错误:每行输出必须由唯一的键组合标识。密钥共享 2 行:使用 Unnest_token 和 spread 时
- sonarqube - 部署 Sonarqube 到 Kubernetes 时,服务停止并抱怨 Mulesoft 插件 jar 文件不是插件