Why does the modulus operator behave differently in Perl and PHP?
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;
}
精彩评论