我今天在大学做了一个练习,它是一个JavaScript程序来计算考试中学生的平均分数。
这是我的代码:
<!DOCtype html>
<html>
<head>
<title>While loop</title>
</head>
<body>
<script>
//The total score of all pupils
var total = 0;
//The number of scores
var count = 1;
while (count <= 10) {
grade = prompt("Insert the grade:");
total = total + grade;
count++;
}
var average = +total / 10;
document.write("The average is " + average);
</script>
</body>
</html>
我投入的价值是10到100上升10。所以我放入了这10个值&#34; 10,20,30,40,50,60,70,80,90,100和#34;而不是获得平均值,我并没有得到所有这些价值。
我做错了什么?
答案 0 :(得分:5)
grade = prompt("Insert the grade:");
是问题所在。提示将您的输入作为字符串,在JS中,添加两个字符串只是连接值。所以解析你的输入:
grade = +prompt("Insert the grade:"); //+ is shorthand for casting to a number
或使用parseInt
grade = prompt("Insert the grade:");
var numberGrade = parseInt(grade);
仅供参考 - 您添加的所有数字必须是整数 - 否则它最终会再次作为字符串结束,例如:
10 + 10; //20
10 + "10" //1010
10 + 10 + "10" //2010
答案 1 :(得分:1)
更改
total = total + grade;
至
total = total + parseInt(grade);
当你写total = total + grade
js连接总数和成绩为字符串