我想在php中计算偶数,奇数

我想计算偶数,奇数。如果有2个偶数,我只数1个偶数,如果有2个奇数,我只数1个奇数


<?php 

$myarray = array(5,5,0,1,2,1,1,6,1);


for ($i = 0; $i < count($myarray); $i++) { 

  echo "Index ", $i, ", value ", $myarray[$i], ": ";


  if ($myarray[$i] % 2 == 0) {

    echo "even\n";

  }

  else {

    echo "odd\n";

  }

}

?>

输入=[5,5,0,1,2,1,1,6,1]


output =  5 :1(total(5) odd one),

          1:2 (total(1) odd two)


撒科打诨
浏览 155回答 4
4回答

慕工程0101907

创建计数器$evens和odds. 然后使用 循环遍历数组中的元素检查 number 是否为奇数Ternary Operator (condition) ? true : false;,$num & 1如果 number 为 则返回 true odd。$nums = array(5,5,0,1,2,1,1,6,1);$odds = $evens = 0;foreach ($nums as $num) {&nbsp; &nbsp; &nbsp;$num & 1 ? ++$odds : ++$evens;}echo "Odds: $odds, Evens: $evens"; //Odds: 6, Evens: 3

www说

只需计算 的数量odds,因为如果我们计算数组中的数量,通过将数组中的元素数量减去 的Odds数量就可以很容易地知道 的数量EvensOdds$nums = array(5,5,0,1,2,1,1,6,1);$odds = 0;foreach ($nums as $num) {&nbsp; &nbsp; $odds += $num % 2;}$evens = count($nums)-$odds;echo "Odds: $odds, Evens: $evens"; //Odds: 6, Evens: 3

桃花长相依

当您循环遍历数组时,使用两个变量来跟踪赔率和偶数。$my_array = array( 5, 5, 0, 1, 2, 1, 1, 6, 1 );$odd = $even = 0;foreach ( $my_array as $number ) {&nbsp; &nbsp; $number % 2 == 0 ? $even++ : $odd++;}printf( 'Odd: %s | Even: %s', $odd, $even );

MMMHUHU

<?php$num = array(23,12,11,9,6,7,4,5,3);$n=count($num);$even = 0;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;$odd = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; for( $i = 0 ; $i < $n; $i++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if ($num[$i] & 1 == 1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $odd ++ ;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $even ++ ;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; echo "Number of even elements = $even&nbsp; &nbsp; &nbsp; &nbsp; and Number of odd elements = $odd" ;&nbsp; &nbsp;&nbsp;?>
打开App,查看更多内容
随时随地看视频慕课网APP