我是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);
}发布于 2014-05-05 10:28:24
您应该使用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;发布于 2014-05-05 10:42:42
这应该是可行的:
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();https://stackoverflow.com/questions/23463894
复制相似问题