Results 1 to 5 of 5

Thread: Javascript Homework Help

  1. #1
    Join Date
    Jul 2003
    Posts
    1,524

    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
    Last edited by Jeff; 04-07-2008 at 02:29 AM.

  2. #2
    Join Date
    Jul 2003
    Location
    Sydney, Australia
    Posts
    5,644
    Wait a few hours and I'll ask my guru if he can help.


  3. #3
    Join Date
    Jul 2003
    Posts
    1,524
    Thanks, I'll definitely be looking. I spent hours on this at work tonight. It is so frustrating.

  4. #4
    Join Date
    Jul 2003
    Location
    Sydney, Australia
    Posts
    5,644
    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


  5. #5
    Join Date
    Jul 2004
    Location
    Sussex, UK
    Posts
    3,734
    pretty much you need
    num = parseInt(num)
    in the for loop otherwise it assumes its a string and concatenates the input in a string.

Posting Permissions

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