1. 程式人生 > >JS基礎——陣列綜合練習(輸入班級人數及成績,求總成績、平均成績、最高分、最低分)

JS基礎——陣列綜合練習(輸入班級人數及成績,求總成績、平均成績、最高分、最低分)

原始碼:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<script>
    var perCount = parseInt(prompt("請輸入班級人數:"));
    var perScores = [];
    for (var i = 0; i < perCount; i++) {
        perScores[perScores.length] = parseInt(prompt("請輸入第" + (i + 1) + "個學生的成績:"));
    }
    var sum = 0;
    var max = perScores[0];
    var min = perScores[perScores.length - 1];
    for (i = 0; i < perCount; i++) {
        sum += perScores[i];
        if (max < perScores[i]) {
            max = perScores[i];
        }
        if (min > perScores[i]) {
            min = perScores[i];
        }
    }
    console.log(perScores);
    console.log("總成績:" + sum);
    console.log("平均成績:" + sum / perCount);
    console.log("最高分:" + max);
    console.log("最低分:" + min);
</script> </body> </html>