我是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);
}
答案 0 :(得分:2)
您应该使用total
定义var
并分配到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;
答案 1 :(得分:0)
这应该有效:
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 强>