Log in

View Full Version : Javascript Homework Help



Jeff
04-07-2008, 01:02 AM
I am trying to create a function to take the average of a set of numbers that the user enters. I am not having much luck


<html>
<head>
<script language="JavaScript" type="text/javascript">
function getAvg(howmany) {
for (i=0;i<howmany;i++) {
var num = prompt("Please enter the number", "")
var total += num
var avg = total / howmany
}
return(avg)
}

</script>
</head>
<body>
<script language="JavaScript" type="text/javascript">
var amount = prompt("Please enter the amount of numbers you wish to average", "")
getAvg(amount)
</script>
</body>
</html>

vaughan
04-07-2008, 04:20 AM
Wait a few hours and I'll ask my guru if he can help.

Jeff
04-07-2008, 04:34 AM
Thanks, I'll definitely be looking. I spent hours on this at work tonight. It is so frustrating.

vaughan
04-07-2008, 07:44 AM
Michael replying~
You don't need to declare variables with the 'var'. Javascript is annoying because if it gets any kind of error it makes the whole thing not work.

I had something like this;


<html>
<head>
<script language="JavaScript" type="text/javascript">
function getAvg() {
amount = prompt("Please enter the amount of numbers you wish to average", "")
num = 0
total = 0
avg = 0


for (i=0;i<amount;i++) {
num = prompt("Please enter the number", "")
total += num
}
avg = total / amount
document.write('Average is: ' + avg)
return(avg)

}

</script>
</head>
<body>
<script language="JavaScript" type="text/javascript">
getAvg();

</script>
</body>
</html>









but I think the algorithm is wrong, :-(. I havent really sat down to work it all out properly though.. Good luck with it anyway.
-M

Empty_5oul
04-07-2008, 10:17 PM
pretty much you need
num = parseInt(num)
in the for loop otherwise it assumes its a string and concatenates the input in a string.