【问题标题】:what is wrong in this find average and total?这个查找平均值和总数有什么问题?
【发布时间】:2014-05-29 04:45:29
【问题描述】:

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

<?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>");
?>

【问题讨论】:

  • 你告诉我们“出了什么问题”
  • 旁注:你真的不需要在那些回声上加上括号
  • @sectus 这个网站不是用来提问的吗?你为什么这么消极?如果您不打算提供帮助,为什么还要费心发表评论?
  • 所有这些人只是复制代码而不是测试。没有注意到 OP 有 $for 而不是 for.....
  • 遇到问题时要更具体。 “这是我的代码,它是错误的”——这不是一个好问题。打印所有错误消息,显示预期值和输出值。告诉我们你尝试了什么。

标签: php average


【解决方案1】:

$score 是一个数组,不能作为整数相加。

尝试: $total+=$score[$a]

它也应该是

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

【讨论】:

    【解决方案2】:

    改成for循环语句内部

    $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>");
    ?>
    

    【讨论】:

      【解决方案3】:

      您的代码中有更多语法错误,例如 $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);
      

      【讨论】:

        【解决方案4】:

        如果您查看您的循环,您每次都替换 $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;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多