javascript - 输入分数并计算平均值

标签 javascript arrays loops

我对 JavaScript 很陌生,尽管我知道它应该很简单,所以请帮忙! 我知道有一些类似的主题,但我需要使用这个模板

这是我的作业:

允许用户输入七个不同的分数 计算所有这些分数的平均值 在屏幕上显示平均值

enter image description here

到目前为止我所拥有的:

// init vars, get input from user
var scores = [1,2,3,4,5,6,7];

score[0] = (prompt("Type in a Score 1 of 7") )
score[1] = (prompt("Type in a Score 2 of 7") )
score[2] = (prompt("Type in a Score 3 of 7") )
score[3] = (prompt("Type in a Score 4 of 7") )
score[4] = (prompt("Type in a Score 5 of 7") )
score[5] = (prompt("Type in a Score 6 of 7") )
score[6] = (prompt("Type in a Score 7 of 7") )

function calculate() {
    for (var i = 0; i < scores.length; i++) {
        total += score[i];
    }
    average = (total / scores.length).toFixed(2);
}

function getscores() {
    while (scores.length < 7) {
        scores.push(parseInt(prompt("Please input a score")));
    }
}

getScores();
calculate();
showScores();

function showScores() {
    document.write("The average of those scores is: " + average);
}

最佳答案

您应该使用 var 定义 total 并将其分配给 0:

 function calculate() {
   var total = 0;
   for (var i = 0; i < scores.length; i++) {
     total += scores[i];
   }
    average = (total / scores.length).toFixed(2);
 }

此外,您应该将 average 设置为全局,就像您对范围所做的那样:

var average;

关于javascript - 输入分数并计算平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23463894/

相关文章:

javascript - 我如何使用 php 和 mysql 在单行引导 slider 中获取不同的数据结果

php - 如何制作一个php模板引擎?

r - 使用 R,一次循环两个文件

c - 我的 for 循环出了什么问题?

javascript - Firebase 云函数 : "status" :"INVALID_ARGUMENT"

javascript - setInterval时间不精确

c++ - C/C++ 中无数组的单行快速输入字符串

JAVA - 对象无法添加到对象数组 - NullPointerException

matlab - 从 MATLAB 中的前一个数字中减去任何数字

javascript - 获取空的json数据