我试图找到数组的总和,但是代码将所有数字放在一起,但不是为了求和它们。就像,如果我有90,95,100的等级,总和将是09590100.第一个FOR循环经过测试并可以将等级推入数组,但第二个for循环在某处证明是错误的。
var numOfGrades = prompt("How many total assignments?");
var grades = [];
var sum = 0;
var grade = 0;
var avg = 0;
for (var i = 0; i < numOfGrades; i++) {
grade = prompt("Type in score");
grades.push(grade);
}
for (var j = 0; j < grades.length; j++) {
sum += grades[j];
}
avg = (sum / grades.length)
答案 0 :(得分:3)
这个问题是您正在以字符串形式阅读输入 - 您需要将其解析为数字
https://www.google.ca/search?q=javascript+convert+string+to+integer
for (var i = 0; i < numOfGrades; i++) {
grade = prompt("Type in score");
grades.push(parseInt(grade));
}
答案 1 :(得分:1)
您需要使用parseInt函数。 Javascript会将这些成绩值视为字符串。在对它们执行计算之前,您需要显式地使它们成为整数。见这个例子
http://jsfiddle.net/conkman/5Eu7T/
$(document).ready(function(){
var numOfGrades = prompt("How many total assignments?");
var grades = [];
var sum = 0;
var grade = 0;
var avg = 0;
for (var i = 0; i < numOfGrades; i++) {
grade = prompt("Type in score");
grades.push(grade);
}
for (var j = 0; j < grades.length; j++) {
sum += parseInt(grades[j]);
}
avg = (sum / grades.length);
alert(avg);
});
parseInt周围的文档: http://www.w3schools.com/jsref/jsref_parseint.asp