从PHP数组中提取信息。

huangapple go评论47阅读模式
英文:

Extract information from array in php

问题

我必须从表单输入中获取以下信息

Jack - 80,55,77
Jim - 50,60,70

从这些信息中,我必须提取成绩并找到平均值
我的代码问题如下:
在第一种情况下,一切都正常,80+55+77/3
在第二种情况下,我的代码取得了80+55+77+50+60+70,我只需要50+60+70

输出必须是:
Jack的平均成绩是70
Jim的平均成绩是60

这是我的代码:

<?php
$elements = [];
$sum=0;
while (FALSE !== ($line = fgets(STDIN))) {
  $elements[] = trim($line);
}
foreach ($elements as $element) {
    $input = explode( ' - ', $element );
    $grades=explode(",",$input[1]);

    for ($i=0; $i < count($grades); $i++) { 
        $sum+=$grades[$i];
    }
    print "<p>". $input[0]."的平均成绩是".floor($sum/count($grades))."</p>";
}
?>
英文:

I have to take from the form input the following information

Jack - 80,55,77
Jim - 50,60,70

From this information, I have to extract the grades and find the average
The problem with my code is as follows:
In the first case, everything is fine 80+55+77/3
In the second case, my code takes 80+55+77+50+60+70 I need only 50+60+70

The output has to be:
Jack's average grade is 70
Jim's average grade is 60

This is my code:

&lt;?php
$elements = [];
$sum=0;
while (FALSE !== ($line = fgets(STDIN))) {
  $elements[] = trim($line);
}
foreach ($elements as $element) {
    $input = explode( &#39; - &#39;, $element );
    $grades=explode(&quot;,&quot;,$input[1]);

    for ($i=0; $i &lt; count($grades); $i++) { 
        $sum+=$grades[$i];
    }
    print &quot;&lt;p&gt;&quot;. $input[0].&quot;&#39;s average grade is &quot;.floor($sum/count($grades)).&quot;&lt;/p&gt;&quot;;
}
?&gt;

答案1

得分: 0

你需要为每个学生重置总和:

$elements = [];
while (FALSE !== ($line = fgets(STDIN))) {
    $elements[] = trim($line);
}
foreach ($elements as $element) {
    $input = explode(' - ', $element);
    $grades = explode(',', $input[1]);
    $sum = 0;
    for ($i = 0; $i < count($grades); $i++) {
        $sum += $grades[$i];
    }
    print "<p>" . $input[0] . "'s average grade is " . floor($sum / count($grades)) . "</p>";
}

请注意,我已将代码中的 HTML 标签部分保持原样,因为它们不需要翻译。

英文:

You need to reset sum for each student:

&lt;?php
$elements = [];
while (FALSE !== ($line = fgets(STDIN))) {
    $elements[] = trim($line);
}
foreach ($elements as $element) {
    $input = explode( &#39; - &#39;, $element );
    $grades=explode(&quot;,&quot;,$input[1]);
    $sum = 0;
    for ($i=0; $i &lt; count($grades); $i++) { 
        $sum+=$grades[$i];  
    }
    print &quot;&lt;p&gt;&quot;. $input[0].&quot;&#39;s average grade is &quot;.floor($sum/count($grades)).&quot;&lt;/p&gt;&quot;;
}
?&gt;

huangapple
  • 本文由 发表于 2023年5月18日 02:08:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76275038.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定