I wrote javascript code which tells you the average of numbers. You enter the numbers by pressing the add button. The added numbers will be shown on the screen. If you don't enter any number, A text "empty string" will be shown and if you enter numbers this message will be not shown and the average of entered numbers will be shown. But the problem is that, even after entering the numbers still the text "empty string" is shown. And I can't find out why. When I wrote this code without giving user the ability to enter numbers and provide numbers by myself. The same code was working correctly and was showing average but when I added the function to enter numbers... the "average code" start troubling. Kindly, give a look at this NOOB programmers code and correct my code. Thank you.
Code:
<body>
<h2>Averge Function</h2>
<p>Press the button below to add numbers in the array:<br>
<button onclick="addNum()">Add</button>
</p>
<p id="numInArray"></p>
<p id="average"></p>
<!--JS Code-->
<script>
var grades = [];
function addNum() {
var grade = prompt("Add a number");
grades[grades.length] = grade;
document.getElementById("numInArray"). innerHTML =
"Numbers in array are: " + grades;
}
var sum = 0;
if (grades.length > 0) {
for (index = 0; index < grades.length; index++) {
sum += grades[index];
}
document.getElementById("average").innerHTML = sum/grades.length;
}
else {
document.getElementById("average").innerHTML = "Empty string";
}
</script>
</body>
Aucun commentaire:
Enregistrer un commentaire