Results 1 to 2 of 2

Thread: Min and Max number from a Prompt

  1. #1
    Join Date
    Nov 2006
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Min and Max number from a Prompt

    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

  2. #2
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Code:
    <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>
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •