这个查找平均值和总数有什么问题?

时间:2014-05-29 04:45:29

标签: php average

是的我是一个菜鸟......我正在尝试自己学习php,这太难了。 AH

<?php
$score=array(80,90,90,99,78);

    $total=0;
    $for ($a=0; $a<=5; $a++) {
            $total=$score+1;
    }
    $avg = $total/5;
    echo ("score $score[0], $score [1], $score [2], $score [3], $score [4] <br>";
    echo ("total $total, average $avg <br>");
?>

4 个答案:

答案 0 :(得分:2)

作为数组的$ score不能作为整数添加。

尝试: $总+ = $得分[$ A]

它也应该是&lt; 5,不是&lt; = 5,或者更好的是使用count($ score)以防你想要在数组中添加或删除:

$total=0;
for ($a=0; $a<count($score); $a++) {
        $total+=$score[$a];
}
$avg = $total/count($score);

答案 1 :(得分:1)

更改为循环语句内部

$total=$score+1;

$total+=$score[$a];

更新:许多错误都会尝试此代码

<?php
$score=array(80,90,90,99,78);

    $total=0;
    for ($a=0; $a< count($score); $a++) {
           $total+=$score[$a];
    }
    $avg = $total/count($score);
    echo ("score $score[0], $score[1], $score[2], $score[3], $score[4] <br>");
    echo ("total $total, average $avg <br>");
?>

答案 2 :(得分:0)

您的代码中有更多语法错误,例如$forecho statement。您需要将所有值添加到$total

 $score=array(80,90,90,99,78);
 $total=0;
 for ($a=0; $a<=count($score); $a++) {
    $total = $total+$score[$a]; //$total+=$score[$a];
 }
 $avg = $total/5;
 echo "score". $score[0]. $score [1]. $score [2].$score [3]. $score[4] ."<br>";
 echo "total $total, average $avg <br>";

或使用简短代码: - 使用array_sum()count()

  $score = array(80,90,90,99,78);
  echo $total = array_sum($score);
  echo $avg = $total/count($score);

答案 3 :(得分:-1)

如果你看一下你的循环,你每次都会用新值替换 $ total。你没有总结得分。因此,您必须使用$total = $total + something;

接下来是,由于$ score是一个数组,你应该使用$score[index](在这种情况下,索引是$ a)而不是$score来引用数组中的元素。

这将是结果:

$total=0;
$for ($a=0; $a<=5; $a++) {
    $total=$total+$score[$a]+1;
}
$avg = $total/5;