值一起显示,而不是作为新值显示

Values show together instead of as a new value

本文关键字:显示 新值 一起      更新时间:2023-09-26

我今天在大学做了一个练习,它是一个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个值"10,20,30,40,50,60,70,80,90,100",而不是得到平均值,而是将所有这些值并列得到。

我做错了什么?

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

改变total = total + grade;total = total + parseInt(grade);

当你写total = total + grade js时将total和grade连接为字符串