PDA

View Full Version : Min and Max number from a Prompt



allanibanez
11-10-2006, 09:00 PM
Hi, i was hoping for a bit of help.

Basically i have this code.

<html>
<head>
<title>Averaging program</title>
<script language=JavaScript><!--
var number;
var total = 0;
var count;
var amount = prompt("Enter amount: ","");
for (count=1; count<=amount; count++) {
number = prompt("Enter a number: ","");
number = parseFloat(number);
total = total + number;
}
var average = total / amount;
document.write("The average of "+amount+" numbers is ");
document.write(average);
//--></script>
</head>
<body>
<p>
</body>
</html>

but i need to somehow display the largest and smallest number that the user enters into the prompt boxes. Im not really sure how to go about it, as the amount of numbers the user enters is down to them, so i cant even use the math.max function (as far as i can see anyway)

any help would be great. thanks

Twey
11-10-2006, 09:37 PM
<script type="text/javascript">
function maxFrom(arr) {
var ret = arr[0];
for(var i = 1; i < arr.length; ++i)
if(arr[i] > ret)
ret = arr[i];
return ret;
}

function minFrom(arr) {
var ret = arr[0];
for(var i = 1; i < arr.length; ++i)
if(arr[i] < ret)
ret = arr[i];
return ret;
}

var n, total, nums = [];
while((n = prompt("Enter a number:")) !== null)
total += (nums[nums.length] = isNaN(n = parseFloat(n)) ? 0 : n);
alert("Average of " + nums.length + " numbers: " + (total / nums.length));
alert("Largest number: " + maxOf(nums));
alert("Smallest number: " + minOf(nums));
</script>