-
Javascript Homework Help
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
PHP Code:
<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>
-
Wait a few hours and I'll ask my guru if he can help.
-
Thanks, I'll definitely be looking. I spent hours on this at work tonight. It is so frustrating.
-
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;
PHP Code:
<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
-
pretty much you need
num = parseInt(num)
in the for loop otherwise it assumes its a string and concatenates the input in a string.