值一起显示,而不是作为新值显示
Values show together instead of as a new value
我今天在大学做了一个练习,它是一个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连接为字符串
相关文章:
- jquery日期选择器显示与值不同的文本
- 如何避免X轴显示十进制值
- 当我单击下一个或上一个按钮时,datatable显示旧值
- 用javascript在html显示列表中显示新成员
- $$hashKey在Angular中push()新对象时未生成新值
- 点击后,永久更改内容;悬停时,简要显示新内容
- text()将保留旧值,但在DOM上显示新值
- Knockout Force在设置新值时通知订阅者可观察到的值
- 服务器上的 Meteor.publish 不会在客户端上显示新文档
- 如何在提示下获取和使用从window.onbeforeunload事件的返回语句显示的值
- Javascript / JQuery循环访问已发布的ajax数据字符串以为其分配新值
- 为nouislider设置新值已达到最大数量
- 尝试在不刷新页面的情况下单击按钮显示新的随机值
- Jquery 最小值和最大值显示新页面
- Select2下拉列表允许在用户键入时按用户显示新值
- 在javascript上使用onClick增加变量值,并在HTML表单上显示新值
- 值一起显示,而不是作为新值显示
- 显示新的输入值(添加空格)
- 在页面重定向后保留表单值,使用JavaScript在新表单中显示这些值
- 显示新页面之前函数的绑定值