【问题标题】:Input scores and count the average输入分数并计算平均值
【发布时间】:2014-05-05 10:49:04
【问题描述】:

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

这是我的任务:

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

到目前为止我所拥有的:

// 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);
}

【问题讨论】:

  • 你能解释一下出了什么问题吗?
  • 具体需要什么帮助?除非您告诉我们您遇到了什么问题,例如您看到了什么错误或意外行为,否则我们无法提供任何帮助。

标签: javascript arrays loops


【解决方案1】:

您应该用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;

【讨论】:

  • “分数”也未定义
  • @BrendanScarvell,你是什么意思,score 未定义?
  • @Brendan Scarvell:我认为这是 OP 的错字。更新了我的答案
  • @Atutouato :他的意思是有一个数组scores,但是OP在for循环中使用了一个数组score
  • 他在顶部使用 score 作为数组,而没有将其定义为数组,这会抛出ReferenceError
【解决方案2】:

这应该可行:

var score = [];

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

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

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

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

Working JSFiddle Example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 2014-04-27
    • 1970-01-01
    • 2013-11-05
    • 1970-01-01
    • 2021-07-07
    相关资源
    最近更新 更多