JavaScript总和平均最高分

时间:2015-05-20 23:31:08

标签: javascript

function getScore() {
    var score = 0;
    var sum = 0;
    while (score != -99) {
        sum = sum + score;
        score = parseInt(prompt("Enter a score or enter -99 when you're done:"," "));
    } 
    document.write("<p>The score total: " + sum + ".</p>");
} 

现在,当我点击按钮时,它显示总和,我想知道我是否想获得输入的平均,最高和最低分数,我该怎么办?

4 个答案:

答案 0 :(得分:0)

将数字放在数组中,然后您可以使用everage,min和max函数

答案 1 :(得分:0)

&#13;
&#13;
function getScore() {
    var average = 0
    var sum = 0;
    var highest = 0;
    var lowest = 0;
    var count = 0
    var score = 0;
    
    
    while (score != -99) {
        score = parseInt(prompt("Enter a score or enter -99 when you're done:", " "));
        if(score == -99)
            break;
        if(count == 0)
            lowest = score;
        count++;
        sum += score;
        average = sum/count;
        if(score > highest)
            highest = score;
        if(score < lowest)
            lowest = score;
        
    }
    
    return {"count": count, "sum": sum, "average": average, "highest": highest, "lowest": lowest};
}
console.log(getScore());
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您应该评估当前值是大于还是小于之前的

&#13;
&#13;
var nmbs = [1, 34, 45, 65, 9],
    min = nmbs[0], 
    max = nmbs[0];

for(i in nmbs){
    //check max&min
    if(nmbs[i] > max){
        max = nmbs[i];
    }
    if(nmbs[i] < min){
        min = nmbs[i];
    }
}

document.querySelector(".result").innerHTML = "Max = "+max+" & Min = "+min;
&#13;
<p class="result"></p>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

试试这个。我用数组替换了sum变量。

function getScore() {
    var score = 0;
    var scores = [];
    while (score != -99) {

        score = parseInt(prompt("Enter a score or enter -99 when you're done:"," "));
        if (score != -99) scores.push(score);
    } 
    var sum = 0;
    var minvalue = 0;
    var maxvalue = 0;
    for(var t = 0; t < scores.length; t++) { 
        sum += scores[t];
        if (t === 0) {
            // we default the min/max on the first time through
            minvalue = scores[t];
            maxvalue = scores[t];
        } else {
            // after that we start comparing.
            if (scores[t] < minvalue) { minvalue = scores[t]; }   
            if (scores[t] > maxvalue) { maxvalue = scores[t]; }
        }
    }
    var avg = sum / scores.length;

    document.write("<p>The score total: " + sum + ", average: " + avg + ", max: " + maxvalue + ", min: " + minvalue + "</p>");
} 

**基于评论的编辑** 我在上面的函数中添加了MaxMin值。专门针对您的评论,如果您使用此解决方案,-99永远不会出现在scores的集合中。如果是,请找出它添加到scores数组的位置并阻止它。