我希望能够有一个用户输入多个成绩,然后有Javascript平均这些成绩输入。当用户完成输入等级时,他们可以单击取消并关闭Propmt框,如果他们根本没有输入任何等级(默认值为0),则程序显示没有输入任何等级。
我在这方面是个新手!我在我的大学里学了一门javascript课程,这有点让人困惑,因为老师不教我!我们所要引用的就是W3schools,这个东西根本没有列出!
这是另一种解释:“开发一个程序,允许老师输入任意数量的成绩,执行平均计算,然后将结果显示在语法句子中。程序还必须告诉用户是否没有输入成绩。您需要使用循环和‘if else’语句。请确保声明所有变量,并测试除以零的可能性。”
<script type = "text/javascript">
var gradeCounter = 0,
gradeValue = 0,
total = 0,
average, grade;
var sum = 0;
var i = 0;
while (gradeValue != -1 && gradeValue <= 100) {
//Prompt the user
grade = prompt("Enter Grades, -1 to Quit:", "0");
//Parse the prompt result to a int
sum += parseInt(grade);
i++;
if (i >= 0 && grade != null) {
document.getElementById("average").innerHTML = "The average of the grades you've entered are " + sum / i + ".";
} else {
document.getElementById("error").innerHTML = "There were no grades entered";
}
} </script>
再次感谢!
发布于 2014-12-09 10:16:40
这样就可以了
已更新
再次更新
// note: the dom must be ready before execution
var btn = document.querySelector('button'),
res = document.getElementById('average');
btn.addEventListener('click', function(e) {
var val = prompt('Enter comma delimited grades to average');
val = val.length ? val.replace(/\s/g, '').split(',') : '';
var count = val.length || 0; // no 0 division
if (!count) {
res.innerHTML = 'you must enter comma delimited numbers to average';
return;
} else {
var average = val.reduce(function(a, b) { // is a loop
return +a + +b;
});
res.innerHTML = (average /= count).toFixed(1);
}
});html
<button id="avgBtn">Prompt</button>
<p>Average: <span id="average"></span></p>发布于 2014-12-09 10:52:37
var grades = [];
// initialize the array that will store the entries
var sum = 0;
// initialize the variable that will add the array values together
var average;
// initialize the variable that will contain the final result
var invalid = [];
// initialize the variable that will be used to make sure the user inserts something
for (i = 0; i < 5; i++) {
// repeat the following code 5 times
grades[i] = prompt("Please enter a grade. (You will be asked for 5 grades)", "");
// ask the user for a grade and store it to the array
}
for (i = 0; i < grades.length; i++) {
if (grades[i] === "" || grades[i] === null) {
invalid[invalid.length] = grades[i];
}
}
if (invalid.length !== 5) {
for (i = 0; i < grades.length; i++) {
// repeat this code the same amount of times as there are entries in the array (5)
sum += Number(grades[i]);
// add the entries together. make sure they are numbers using the Number() function
}
var average = sum / grades.length;
// divide the added entries by the number of entries (again, 5)
alert("The average of all of your numbers is: " + average);
// alert the user of the completed average
} else {
alert('You need to enter grades for this to work! Please reload the page to try again.');
}
https://stackoverflow.com/questions/27370076
复制相似问题