Array in PHP that is not getting values

0

The purpose 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 they are negative I have to count +1 to a counter (ie add positive 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 positives or show the array.

I assume the array 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>
    
asked by anonymous 24.10.2017 / 17:34

3 answers

2

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

$vec = $temp;

In this way it would only return the first value:

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

Result:

<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>

Output:

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
    
24.10.2017 / 17:47
1

Just to differentiate yourself from other responses, you can not use if and actually do not use > or < if you want.

You can create an array and do the same operation regardless of whether or not the value is negative or positive, then just get the data you need, for 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;

Try this here.

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

Then, in both cases, we insert the result into the array and just show what it takes.

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;
    
24.10.2017 / 20:30
0

You have incremented values in the variable $pos but tried to display the values of $sum , another thing you are not doing is to display the values of the vector at each iteration.

See it working

Here is the complete 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();
?>
    
24.10.2017 / 17:38