英文:
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:
<?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]."'s average grade is ".floor($sum/count($grades))."</p>";
}
?>
答案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:
<?php
$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>";
}
?>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论