PHP array that is not getting values

Asked

Viewed 406 times

0

The goal of the exercise was to create an array of 20 numbers ranging from -100 to 100. I have to distinguish between negative and positive values. If it is positive I have to add the value in its entirety to a variable and if it is negative I have to count +1 to a counter (that is, add positives and count the number of negatives).

For some reason I am able to count the negatives but I am not able to calculate the sum of the positives nor show the array.

I assume it is the array that is not being saved correctly. My code is as follows::

<html>
 <head>
     <meta charset="UTF-8">
  <title>PHP Test</title>
 </head>
 <body>

    <?php   
     function random(){
         $vec = array();
         $neg = 0;
         $pos = 0;

            for ($i=1; $i<=20; $i++) {
                $temp = rand(-100, 100);
                $vec = $temp;

                if ($temp <= 0) {
                    $neg++;
                } else {
                    $pos+=$vec;
                }
            }


         echo "Soma dos Positivos </br>" . $sum . "Numero de negativos " . $neg . "</br>";

                 for ($i=1; $i<=20; $i++) {
                     return $vec[$i];
                 }        
        } 

        random();
    ?>
 </body>
</html>
  • I had not seen that it was to display at each iteration, I corrected my response from a look :)

3 answers

2


You were not assigning to the vector the value of the correct form:

$vec = $temp;

This way it would only return the first value:

for ($i=1; $i<=20; $i++) {
    return $vec[$i];
} 

Upshot:

<html>
    <head>
        <meta charset="UTF-8">
        <title>PHP Test</title>
    </head>
    <body>
        <?php
        $vec = array();
        $neg = 0;
        $pos = 0;

        for ($i = 0; $i < 20; $i++) {
            $temp = rand(-100, 100);
            $vec[$i] = $temp;

            if ($temp <= 0) {
                $neg++;
            } else {
                $pos += $vec[$i];
            }
        }


        echo "Soma dos Positivos " . $pos .
        "</br>Numero de negativos " . $neg . "</br>";

        for ($i = 0; $i < 20; $i++) {
            echo $vec[$i] . "</br>";
        }
        ?>
    </body>
</html>

Exit:

Soma dos Positivos 756
Numero de negativos 8
19
66
-37
71
-57
89
47
-67
57
83
12
-67
-62
-75
68
-95
69
-77
92
83

1

Just to differentiate from the other answers, you may not use if and actually don’t even use > or < if you want.

You can create an array and do the same operation regardless of whether the value is negative or positive, then just take the data you need, an example:

<?php

$msb = PHP_INT_SIZE * 8;
$resultado = [0 => ['qnt' => 0, 'total' => 0], 1 => ['qnt' => 0, 'total' => 0]];

for ($i = 0; $i < 20; $i++){
    $n = random_int(-100, 100);

    $isNegativo = ($n >> $msb) & 1;
    $resultado[$isNegativo]['qnt'] += 1;
    $resultado[$isNegativo]['total'] += $n;

    echo  $n . PHP_EOL;
}

echo 'Total dos positivos: ' . $resultado[0]['total'] . PHP_EOL;
echo 'Quantidade de negativos: ' . $resultado[1]['qnt'] . PHP_EOL;

Test it out here.

The $isNegativo moves the most significant bit, which will always be -1 or 0, because the >> still keeps the signal. So if he goes -1 we can do the & 1 so that it becomes 1 for negative and 0 for positive.

Then, in both cases, we insert the result into the array and only show what is needed.


Another option using < and if, would be:

<?php

$resultado = [0 => 0, 1 => 0];

for ($i = 0; $i < 20; $i++){
    $n = random_int(-100, 100);

    $resultado[$n < 0] += $n < 0 ? 1 : $n;

    echo  $n . PHP_EOL;
}

echo 'Total dos positivos: ' . $resultado[0] . PHP_EOL;
echo 'Quantidade de negativos: ' . $resultado[1] . PHP_EOL;

0

You incremented the values in the variable $pos but tried to display the values of $sum, Another thing you’re not doing is displaying the vector values at each iteration.

See working

Follow full code, below:

<?php
function random(){
    $neg = 0;
    $pos = 0;
    $vet = array();

    echo "Números sorteados: ";
    for ($i=1; $i<=20; $i++) {
        $temp = rand(-100, 100);
        $vet[$i] = $temp;

        if ($temp <= 0) {
            $neg++;
        } else {
            $pos+=$temp;
        }


        // Obs.: você poderia exibir tudo sem utilizar um array apenas com a variavel $temp, mas como o exercício pediu, deixei a solução abaixo com o array:    
        if($i==20){
            echo $vet[$i] . "</br>";
        }else{
            echo $vet[$i] . ",";
        }

    }

    echo "Soma dos Positivos: " . $pos . "</br> Quantidade de negativos: " . $neg . "</br>";      
} 

random();
?>

Browser other questions tagged

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