如何在 bash 中判断一个值是偶数还是奇数?
我正在建立一个电影数据库,我需要找到收视率的中位数。 我对 bash 真的很陌生(这是我的第一个任务)。
我写道:
let evencheck=$"(($Amount_of_movies-$Amount_of_0_movies)%2)"
if [ $evencheck==0 ]
then
let median="(($Amount_of_movies-$Amount_of_0_movies)/2)"
else
let median="(($Amount_of_movies-$Amount_of_0_movies)/2)+1"
fi
当 $amount_of_movies = 6
和 $amount_of_0_movies = 1
时。我预计中位数是 3。但实际上是 2。为什么呢?
I am building a movie database and I need to find a median for ratings.
I'm really new to bash (it's my first assignment).
I wrote:
let evencheck=$"(($Amount_of_movies-$Amount_of_0_movies)%2)"
if [ $evencheck==0 ]
then
let median="(($Amount_of_movies-$Amount_of_0_movies)/2)"
else
let median="(($Amount_of_movies-$Amount_of_0_movies)/2)+1"
fi
When $amount_of_movies = 6
and $amount_of_0_movies = 1
. I would expect median to be 3. but it's 2. Why is that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
试试这个:
删除 $,然后测试数字相等。
try this:
Removing the $, and then testing for numeric equality.
在你的 if 测试中试试这个:
try this in your if test:
中位数有某种默认值吗?在我看来,它甚至没有进入 if 内部。
Does median have some sort of default value? The way I see it, it's not even going inside the if.
您的代码无法解析。要计算 Bash 中的表达式,您可以说
也就是说,计算算术,如下所示:
$(( ... ))
这就是说,您的问题出在条件中。请参阅
人工测试
。您必须将等号两边都用空格括起来。使用单个等号。
Your code doesn't parse. To evaluate expressions in Bash, you say
That is, evaluate arithmetics like so:
$(( ... ))
That said, your problem is in the conditional. See
man test
.You have to wrap the equality sign with whitespace on both sides. Use a single equality sign.
在您所得到的内容中,最外面的括号和引号都不是必需的(在其他情况下可能是必需的)。此外,在
let
语句中,您可以省略变量名称中的美元符号。如果您使用
(())
形式而不是let
,则可以使用空格来使公式更具可读性。您还可以在if
语句中使用它们:The outermost parentheses and none of the quotes are necessary in what you've got (they may be in other circumstances). Also, in a
let
statement you can omit the dollar sign from variable names.If you use the
(())
form instead oflet
, you can uses spaces to make your formulas more readable. You can also use them inif
statements: