在PHP中,判断数字/变量是奇数还是偶数的最简单、最基本的方法是什么?是不是和mod有关?
我试过几个脚本,但是..谷歌目前还没有交付服务。
发布于 2015-06-01 16:12:44
PHP会自动将null和空字符串转换为零。这种情况也会发生在模数上。因此,代码将
$number % 2 == 0 or !($number & 1)如果值$number = '‘或$number = null,则结果为true。为此,我对它进行了更多的扩展:
function testEven($pArg){
if(is_int($pArg) === true){
$p = ($pArg % 2);
if($p === 0){
print "The input '".$pArg."' is even.<br>";
}else{
print "The input '".$pArg."' is odd.<br>";
}
}else{
print "The input '".$pArg."' is not a number.<br>";
}
}
The print is there for testing purposes, hence in practice it becomes:
function testEven($pArg){
if(is_int($pArg)=== true){
return $pArg%2;
}
return false;
}对于任何奇数,此函数返回1;对于任何偶数,此函数返回0;如果不是数字,则返回false。我总是写=== true或=== false来让我自己(和其他程序员)知道测试是按照预期进行的。
https://stackoverflow.com/questions/7959247
复制相似问题