5

this is my first post. I am writing a program to get input from four input boxes, find out the sum of these four and finding the average. When i do so I get a NaN error, can someone point where I am going wrong. Thanks

<html>
<head>
<title> Average marks </title>

<script type = "text/javascript">

function average(form)
{

scores = new Array(4)

scores [0] = form.mark1.value
scores [0] = new Number(scores[0])
scores [1] = form.mark2.value
scores [1] = new Number(scores[1])
scores [2] = form.mark3.value
scores [2] = new Number(scores[2])
scores [3] = form.mark4.value
scores [3] = new Number(scores[3])


var Sum = 0
var average

for(var x = 0; x < scores.length; x ++)
{
Sum = Sum + scores[x]
average = Sum / scores[x]
}



document.write("The sum of the marks is equal to " + Sum + "<br>")
document.write("The average of these marks is equal to " + average + "<br>")


}

</script>


</head>

<body>

<form>
Enter the first mark : <input type = "text" name="mark1"> <br>
Enter the second mark : <input type = "text" name="mark2"> <br>
Enter the third mark : <input type = "text" name="mark3"> <br>
Enter the fourth mark : <input type = "text" name="mark4"> <br>

<input type = "submit" value = "submit" onclick="average(this.form)">
</form>


</body>
</html>
user1839207
  • 89
  • 1
  • 2
  • 6
  • 5
    1) Never use `new Array`. 2) Never use `new Number`. 3) Always use semicolons at the end of statements. 4) Was one of the marks zero? Because 5) That's not how you average things. – Ry- Nov 20 '12 at 15:11
  • see also direct access to HTML itens for average: http://stackoverflow.com/a/24841587/287948 – Peter Krauss Jul 19 '14 at 14:50

4 Answers4

7

Welcome to Stackoverflow :) We would be glad to help you while learning our tools better. Just one note about the algorithm: move the average calculation command outside the loop:

for(var x = 0; x < scores.length; x ++)
{
  Sum = Sum + scores[x];  //or Sum += scores[x];
}

average = Sum / scores.length;  //length of the array scores is in scores.length

I would use parseInt() instead of new Number() because new Number() creates an object while parseInt() gives you the actual literal value as a result. (better performance).

By the way, don't forget to put var before every variable definition unless you want them to be accessed globaly (bad idea). You did a good job with all variables except scores. The definition should be var scores though that is not the source of this error.

Another point: you can check if the result of parseInt() using isNaN() function. If your numbers can have decimal points, you can use parseFloat() also:

The result of both functions is NaN (not a number) if the conversion from string to number fails.

And finally, I think it is a good idea that you defined the array with a specified length. It improves the readability of your code. However it is not necessary in Javascript as it automatically increases/decreases the length of the array at runtime so you don't have to decide in advance how long it should be. It can be a good thing or a bad thing depending how you use it. But in general you can use var myarr=[]; instead of var myarr= new Array();. However when you want to hint the other developers what's going on, you may specify the array length as well: var myarr=new Array(4);.

And final point for using Stackoverflow: please accept the best answer and "up vote" the other useful answers. This way you will get a score and other people as well.

Good luck

AlexStack
  • 16,766
  • 21
  • 72
  • 104
  • 1
    Please, please, please refer to MDN ([1](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt), [2](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseFloat)) instead of [W3Schools](http://w3fools.com/)! – Ry- Nov 20 '12 at 15:28
  • 2
    +1 for comprehensive answer, but: w3schools is a bad reference. ([why?](http://w3fools.com/)) Use a proper Reference like the [Mozilla Developer Network](https://developer.mozilla.org/en/) for example or [Sitepoint](http://www.sitepoint.com/). – Christoph Nov 20 '12 at 15:29
  • admittedly w3schools often has some nice (non-tech-geeky) explanations and the tryit is nice too, but sadly often their information is outdated, imprecise or worst - plain wrong. – Christoph Nov 20 '12 at 15:34
  • one small edit: ```for(var x = 0, l = scores.length; x < l; x++)``` is considered better approach compared to ```for(var x = 0; x < scores.length; x ++)``` – mido Jan 15 '15 at 01:39
2

You're not averaging the right way... you get the average from the sum (outside of the loop) divided by the number of marks.

Also:

  1. Don't use new Array(4). Predefining array lengths in JavaScript is unnecessary (and can hurt readability and performance).
  2. Don't use new Number(), ever. This creates a Number object, which is a terrible thing that will wreak havoc at some point in time. Use Number(yourString) to cast.
  3. I highly recommend you put semicolons at the end of your statements.
  4. scores is undeclared. (Turn strict mode on, please!)

Anyway, here's what that could look like:

function average(form) {
    var scores = [ // Array literal!
        Number(form.mark1.value), // You could also use a leading +
        Number(form.mark2.value),
        Number(form.mark3.value),
        Number(form.mark4.value)
    ];

    var sum = 0;

    for(var i = 0; i < scores.length; i++) {
        sum += scores[i];
    }

    var average = sum / scores.length;

    // etc.
}
Ry-
  • 218,210
  • 55
  • 464
  • 476
0

The way you build your scores array is needlessly complex. You can just do this:

scores [0] = form.mark1.value;
scores [1] = form.mark2.value;
scores [2] = form.mark3.value;
scores [3] = form.mark4.value;

Then you have an error in your average calculation. The correct way to calculate an average is by summing up all the values and then divide them through the number of values once.

for(var x = 0; x < scores.length; x ++)
{
    Sum = Sum + scores[x];
}
average = Sum / scores.length;
Philipp
  • 67,764
  • 9
  • 118
  • 153
0

To find average first calc sum (e.g. by reduce), then divide - thats all

var Sum = scores.reduce((a,b)=> a+b);    // calculate sum
var average = Sum/scores.length;         // divide by number of elements

<html>
<head>
<title> Average marks </title>

<script type = "text/javascript">

function average(form)
{

scores = new Array(4)

scores [0] = form.mark1.value
scores [0] = new Number(scores[0])
scores [1] = form.mark2.value
scores [1] = new Number(scores[1])
scores [2] = form.mark3.value
scores [2] = new Number(scores[2])
scores [3] = form.mark4.value
scores [3] = new Number(scores[3])


var Sum = scores.reduce((a,b)=> a+b);
var average = Sum/scores.length;

document.write("The sum of the marks is equal to " + Sum + "<br>")
document.write("The average of these marks is equal to " + average + "<br>")


}

</script>


</head>

<body>

<form>
Enter the first mark : <input type = "text" name="mark1"> <br>
Enter the second mark : <input type = "text" name="mark2"> <br>
Enter the third mark : <input type = "text" name="mark3"> <br>
Enter the fourth mark : <input type = "text" name="mark4"> <br>

<input type = "submit" value = "submit" onclick="average(this.form)">
</form>


</body>
</html>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345