Make an application to read 6 values. Calculate and display

Asked

Viewed 49 times

0

Make an application to read 6 values. Calculate and display:

to) The typed sequence;
b) the average of them;
c) values above the average.

I can print the sequence, I can add it up, but it’s not hitting the media, and I’m not getting to do it consistently!

My code so far

<?php
$valores = array();
$media   = 0;
$soma    = 0;
for ($i = 0; $i < 6; $i++) {
    printf("Digite um valor:");
    fscanf(STDIN, "%d \n", $valores[$i]);
}
for ($i = 0; $i < 6; $i++) {
    printf("$valores[$i] \n");
    if ($media < $valores[$i]) {
        $soma  = $soma + $valores[$i];
        $media = $soma / 6;
        if ($valores[$i] >= $media) {
            $acimaM = $valores[$i];
            printf("E os valores acima da media sao " . $acimaM[$i]);
        }
    }
}
printf("A media e " . $media . "\n"); 
  • What is your question? What have you tried?

  • I can print the sequence, I can add it, but it’s not hitting the media, and I’m not getting to do it consistently!

  • <?php $values = array(); $media = 0; $soma = 0; for($i=0;$i<6;$i++){ printf("Type a value:"); fscanf(STDIN,"%d n", $values[$i]); } for($i=0;$i<6;$i++){&#printf("$values[$i]) if($media < values[$$i]){ $sum = $sum + $values[$i]; $media = $sum/6; if($values[$i]>= $media){ $acimaM = $values[$i]; printf("And the above-average values are ". $acimaM[$i]); } } } printf("The media and ". $media." n");

1 answer

2


Your logic for calculating the average is quite confusing and for me it made no sense to the point that I found the code was written almost randomly without being thought of before.

So to understand what was done and to realize how confused you are I recommend you do the table test. With it you’ll realize exactly what your code is doing and you can compare it to what it should be doing.

Alternatively, you can solve the problem like this:

$valores = [];

for ($i = 0; $i < 6; $i++) {
    printf("Digite um valor:");
    fscanf(STDIN, "%d\n", $valores[$i]);
}

$soma  = array_sum($valores);
$media = $soma / 6;

$valoresAcimaDaMedia = array_filter($valores, function ($valor) use ($media) {
    return $valor >= $media;
});

print_r($valoresAcimaDaMedia);

If you enter entries 1, 2, 3, 4, 5 and 6, the average will be 3.5 and therefore the values 4, 5 and 6 will be displayed as output.

Browser other questions tagged

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