比较数字不正常(黑客等级中的Bash脚本)

时间:2017-09-30 19:55:35

标签: bash macos shell sh

根据以下链接中提出的问题:

https://www.hackerrank.com/contests/bash-and-linux-shell-practice/challenges/bash-tutorials---comparing-numbers/problem

我的代码在Mac OSX终端中运行良好,但在Hackerrank中提交相同的代码时,其中一个测试用例失败了。我不确定为什么会这样。非常感谢任何答案。

 read X
 read Y

 if [[ $X > $Y ]]
 then 
   echo "X is greater than Y"
 elif [[ $X < $Y ]]
 then
   echo "X is less than Y"
 else
   echo "X is equal to Y"
 fi

 HackerRank Custom Test Case:

 Compilation Successful
 Input (stdin)
 -100
 100
 Your Output
 X is greater than Y

2 个答案:

答案 0 :(得分:3)

我不确定你为什么会得到那个结果;我得到&#34; X小于Y&#34;在实际的bash中。但是,您的脚本实际上以不同的方式出错:在[[ ]]<>进行字母比较而不是数字比较。要理解这种差异,请考虑[[ 5 < 1000 ]]将出现错误,因为&#34; 5&#34;来自&#34; 1&#34;在字符排序顺序。要进行数字比较,请改用-lt-gt

答案 1 :(得分:2)

您可以使用Bash double-parenthesis上下文((...))与测试上下文[[ ... ]]进行更为典型的算术比较:

x=-5
y=5

if ((x>y)); then 
    echo "X is greater than Y"
elif ((x<y)); then
    echo "X is less than Y"
else
    echo "X is equal to Y"
fi

或者在[[ ... ]]测试中使用integer comparison

if [[ "$x" -gt "$y" ]]; then
    echo "X is greater than Y"
elif [[ "$x" -lt "$y" ]]; then
    echo "X is less than Y"
else
    echo "X is equal to Y"
fi

[[ ... ]]内,<>==测试字符串比较。

这两种方法只适用于整数;要使用浮点数,您需要使用awkbc或其他浮点解释器。请务必在"$x"中使用双引号[[ test ]](( ))

不需要引号和符号

根据用户输入,请务必测试$x$y是否为实际值 数字。好的测试here ......