gpt4 book ai didi

javascript - 值一起显示而不是作为新值

转载 作者:行者123 更新时间:2023-11-28 12:20:04 26 4
gpt4 key购买 nike

我今天在大学做了一个练习,它是一个 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("插入成绩:"); 是问题所在。提示将您的输入作为字符串,在 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

关于javascript - 值一起显示而不是作为新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40359471/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com