...

View Full Version : Having a problem with adding numbers gathered by prompt command



mikhial66
10-02-2008, 07:15 PM
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?

<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>

kansel
10-02-2008, 10:52 PM
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.

mikhial66
10-03-2008, 01:08 AM
That worked. Thanks a lot!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum