我正在尝试使用for循环来获取提示,但是如何从循环中获得平均值?当它在一个带有propmt的var中循环时,它就像var student [0],var student [1]等,它们是如何定义的,所以我可以对它们求平均值?
<html>
<head>
<title>
for
</title>
</head>
<body>
<p>
Average your marks:
<button onclick="myFunction()">Start</button>
</p>
<script type="text/javascript">
function myFunction() {
var Avg = "";
for (var i = 0; i < 5; i++) { // this part makes the prompt below repeat 5 times
// but how would i multiply them.
var Student = prompt("Enter your mark. ");
Avg += // no clue what to do here
}
window.alert(Avg);
}
</script>
</body>
</html>
答案 0 :(得分:1)
function myFunction() {
var sum = 0; // should be initialized to 0 not ""
for (var i = 0; i < 5; i++) {
var mark = prompt("Enter your mark: ");
sum += Number(mark); // sum the marks (convert mark to number because prompt return a string)
}
var avg = sum / 5; // the average is the sum divided by the number of marks which is 5
alert("Your average is: " + avg);
}
答案 1 :(得分:0)
您可以做的是使用从提示输入的内容增加Avg变量。然后通过将总数除以将显示的提示量来获得平均值。
var Avg = 0;
for (var i = 0; i < 5; i++) {
var Student = prompt("Enter your mark. ");
Avg += Student;
}
window.alert(Avg/5);
答案 2 :(得分:0)
这也会提示用户输入标记的学生号码,如果用户没有输入任何认为学生标记为零的内容:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to enter the 5 student's marks</p>
<button onclick="myFunction()">Start</button>
<p id="Average"></p>
<script>
function myFunction() {
var sum = 0;
var students = 5;
for (var i = 1; i <= students; i++) {
var mark = prompt("Please the mark for student " + i, 0);
sum += Number(mark)
}
document.getElementById("Average").innerHTML =
"The average mark was: " + (sum/students);
}
</script>
</body>
</html>