Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
私は負の数では機能しないこのPHP関数を持っています:
function isOdd($num) { return $num % 2 == 1; }
しかし、それは正の数に対して機能します。
まったく同じことを行い、負の数でも機能するこのPerlルーチンがあります
sub isOdd() { my ($num) = @_; return $num % 2 == 1; }
関数の翻訳を間違えましたか? それともPHPのバグですか?
PHP では、 の結果の符号は である被除数x % yの符号ですが 、Perl では である除数の符号です。xy
x % y
x
y
したがって、PHP では、 の結果は、またはの$num % 2いずれかになります。1-10
$num % 2
1
-1
0
したがって、関数を修正して、結果を次のように比較します0。
function isOdd($num) { return $num % 2 != 0; }