How to calculate the Quantity of the even numbers of this vector?

Asked

Viewed 980 times

-3

Create a vector with 7 integer elements. Print the largest and smallest, without sorting, the percentage of even numbers. Only this percentage is missing.

         echo "Maior valor: ".max($num);
         echo "</br> Menor valor: ".min($num)."</br>";

         foreach ($num as $numero){
                echo "$numero ";

         }


    ?>
</body>

1 answer

0


Check that the rest of the division of each number by 2 is equal to 0. If it is, add to a counter.

<?php
// Porcentagem de pares
$array = Array(1, 2, 3, 4, 5, 6);
$contador = 0; // Responsavel por contar o numero de pares
foreach($array as $numero) {
    if($numero % 2 == 0) {
        $contador++;
    }
}
$porcentagemPares = ($contador/6)*100; //Divide o numero de pares pelo numero total de elementos e multiplica por 100
echo "Porcentagem de pares " .$porcentagemPares. "%";

Working example: https://ideone.com/p9kBix

  • Thanks! : ) Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.