多次元配列 / ch12 — 多次元配列の総合演習 / 演習 02
📝 ドリル 02 — 教科ごとのクラス平均を出力
問題
標準入力で 3 行のデータが与えられます。各行は次の形式です。
名前,国語の点,数学の点,英語の点
入力例:
太郎,60,80,100
花子,90,80,70
次郎,90,80,100
各教科のクラス平均 (3 人の平均) を計算し、国語 → 数学 → 英語 の順に 1 行ずつ出力してください。
期待される出力:
80
80
90
採点
php scripts/grade.php v2/topics/06-array-multi/ch12-summary/drill/02-class-average/
ヒント
- 各行を 2 次元配列に組み立てる (名前は無視してよいし、
'scores'キーに点数だけ入れてもよい) - 外側 = 教科 (列)、内側 = 学生 (行) で for ループ
- 各教科について
$sum += $row[$j];し、最後に学生数で割る - 今回は割り切れる点数になっているので
echo $avgでそのまま整数として表示される
テストケース
標準入力
太郎,60,80,100
花子,90,80,70
次郎,90,80,100
期待される出力
80
80
90
📄 starter.php(雛形)
このコードから書き始めてください。
<?php
// TODO: 標準入力 (3 行・"名前,点,点,点" 形式) を読み、各教科のクラス平均を 1 行ずつ出力する
// ヒント:
// $scoresTable = []; // 学生ごとの点数 (3 教科) を並べた 2 次元配列
// while (($line = fgets(STDIN)) !== false) {
// $line = rtrim($line, "\n");
// if ($line === "") continue;
// $cols = explode(",", $line);
// $scoresTable[] = [(int)$cols[1], (int)$cols[2], (int)$cols[3]];
// }
// $subjects = count($scoresTable[0]);
// $students = count($scoresTable);
// for ($j = 0; $j < $subjects; $j++) {
// $sum = 0;
// foreach ($scoresTable as $row) {
// $sum += $row[$j];
// }
// echo ($sum / $students) . "\n";
// }
✅ 解答例を見る(自分で解いてから)
<?php
$scoresTable = [];
while (($line = fgets(STDIN)) !== false) {
$line = rtrim($line, "\n");
if ($line === "") continue;
$cols = explode(",", $line);
$scoresTable[] = [(int)$cols[1], (int)$cols[2], (int)$cols[3]];
}
$subjects = count($scoresTable[0]);
$students = count($scoresTable);
for ($j = 0; $j < $subjects; $j++) {
$sum = 0;
foreach ($scoresTable as $row) {
$sum += $row[$j];
}
echo ($sum / $students) . "\n";
}