在PHP中找出一个数字/变量是奇数还是偶数的最简单最基本的方法是什么? 这和mod有关吗?

我试过一些剧本,但是…谷歌目前没有发送。


当前回答

试试这个带有#Input字段的

<?php
    //checking even and odd
    echo '<form action="" method="post">';
    echo "<input type='text' name='num'>\n";
    echo "<button type='submit' name='submit'>Check</button>\n";
    echo "</form>";

    $num = 0;
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
      if (empty($_POST["num"])) {
        $numErr = "<span style ='color: red;'>Number is required.</span>";
        echo $numErr;
        die();
      } else {
          $num = $_POST["num"];
      }


    $even = ($num % 2 == 0);
    $odd = ($num % 2 != 0);
    if ($num > 0){
        if($even){
            echo "Number is even.";
        } else {
            echo "Number is odd.";
        }
    } else {
        echo "Not a number.";
    }
    }
?>

其他回答

所有偶数除以2都得整数

$number = 4;
if(is_int($number/2))
{
   echo("Integer");
}
else
{
   echo("Not Integer");
}

另一种选择是简单的位检查。

n & 1

例如:

if ( $num & 1 ) {
  //odd
} else {
  //even
}
//checking even and odd
$num =14;

$even = ($num % 2 == 0);
$odd = ($num % 2 != 0);

if($even){
    echo "Number is even.";
} else {
    echo "Number is odd.";
}
$before = microtime(true);

$n = 1000;  
$numbers = range(1,$n);

$cube_numbers = array_map('cube',$numbers);

function cube($n){      
    $msg ='even';       
    if($n%2 !=0){
        $msg = 'odd';
    }               
    return "The Number is $n is ".$msg;
}

foreach($cube_numbers as $cube){
    echo $cube . "<br/>";
}

$after = microtime(true);

echo $after-$before. 'seconds';

$number %2 = 1如果是奇数…所以不用用not even…

$number = 27;

if ($number % 2 == 1) {
  print "It's odd";
}