Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Oct 2008
    Posts
    23
    Thanks
    2
    Thanked 1 Time in 1 Post

    Having a problem with adding numbers gathered by prompt command

    The problem is that when it comes to the line that adds "gradef= gradef + grade;", gradef doesn't add the two numbers. Instead if it was trying to add 50 and 80, it would come out 5080 and not 130. Could some one help me with this problem?
    Code:
    <html>
    <head>
    <title>
    </title>
    </head>
    <body>
    <script language=javascript>
     var x, n, i, gender, grade, counterf, counterm, gradef, gradem, avgm, avgf, gender;
     counterf = 0
     counterm = 0
     gradef = 0
     gradem = 0
     avgm = 0
     avgf = 0
    
     var n = prompt('How many students are there?',' ')
    
    
     for (i=1;i<=n;i++)
      {
    
      var gender = prompt('Gender? For Male type 0, Female type 1',' ')
      var grade = prompt('Grade?',' ')
    
      if (grade > 69)
       {
       if (gender == 1)
        {
        counterf= counterf + 1;
        gradef= gradef + grade;
        }
       else
        {
        counterm= counterm + 1;
        gradem= gradem + grade;
        }
       }
    
    
    
     document.write("Student " + i);
     document.write("'s gender is " + gender);
     document.write(", grade is " + grade);
     document.write("<br />");
     }
     
    
     avgf = gradef / counterf;
     avgm = gradem / counterm;
    
     document.write("<br>There are " + counterf + " female students who passed with an average grade of " + avgf + "<br>");
     document.write("There are " + counterm + " male students who passed with an average grade of " + avgm + "<br>");
    
    </script>
    </body>
    </html>

  • #2
    Regular Coder
    Join Date
    Jul 2002
    Location
    Kansas, USA
    Posts
    487
    Thanks
    0
    Thanked 54 Times in 53 Posts
    When you get input from prompt() it comes back as string type. What you need to do is parse the input as integer* so it knows to add them as numbers and not concatenate them as strings.

    *I assume the grades are integer. If they are numbers with decimals you will need to parse them as floating point.

  • #3
    New Coder
    Join Date
    Oct 2008
    Posts
    23
    Thanks
    2
    Thanked 1 Time in 1 Post
    That worked. Thanks a lot!


  •  

    Posting Permissions

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