开发者

Why does the modulus operator behave differently in Perl and PHP?

开发者 https://www.devze.com 2023-02-14 10:40 出处:网络
I\'ve this PHP function which does not work for negative numbers: function isOdd($num) { return $num % 2 == 1;

I've this PHP function which does not work for negative numbers:

function isOdd($num) 
{
   return $num % 2 == 1; 
}

but it works for positive number.

I have this Perl routine w开发者_如何学Chich does the exact same thing and works for negative number also

sub isOdd()
{
  my ($num) = @_;
  return $num % 2 == 1;
}

Did I make any mistake in translating the function ? or is it PHP bug ?


In PHP the sign of the result of x % y is the sign of dividend which is x but
in Perl it is the sign of the divisor which is y.

So in PHP the result of $num % 2 can be be either 1, -1 or 0.

So fix your function compare the result with 0:

function isOdd($num) { 
  return $num % 2 != 0; 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消