PDA

View Full Version : Resolved Adding User-Given Numbers



Aeche
04-08-2009, 02:01 AM
For a class, I'm trying to create a script that prompts the user for 3 numbers, adds them together, and displays the sum in an alert box. These are the requirements from my teacher:

Using Code Example 4.3 from Lesson Four, write a similar JavaScript that collects three integers from the user, then adds these numbers together (via a function) and returns the results back to the program. These results should then be displayed, via an alert() method, to the user.

NOTE: Your function will not contain any if-statements, but instead will have a line something like "return x+y+z", which means the values of x, y, and z are to be added together and then returned back as the function value.


Here is code example 4.3:

function compareTwo(x, y)
{
if (x==y)
{
return true;
}
else
{
return false;
}
}

// get two integers from the user
var a = prompt("Enter one integer:","");
var b = prompt("Enter another integer:","");

// pass these values to compareXY, defined above.
// if they are the same, the function will return "true",
// otherwise it will return "false".

if (compareTwo(a,b))
{
alert("Your numbers were identical!");
}
else
{
alert("Your numbers were different!");
}


And below is what I have figured out so far. This code will give "ans" as a string of numbers, instead of the sum of the numbers.

function addThree(x,y,z) {
return x+y+z;
}

var a = prompt("Enter one integer:","");
var b = prompt("Enter a second integer:","");
var c = prompt("Enter a third integer:","");

var ans = addThree(a,b,c);

alert("The sum of your numbers is " + ans);

I can tell something is missing, but I just can't figure out what to add! If somebody could help me, that would be awesome, thanks! X3 ♥

Nile
04-08-2009, 02:29 AM
In the function, you have to add numbers, not strings. Turn them into ints using the parseInt method:


return parseInt(x)+parseInt(y)+parseInt(z);


That should do it. ;)

Aeche
04-08-2009, 02:30 AM
It did work!!! Thank you so much, you're awesome! *glomp*

Nile
04-08-2009, 02:31 AM
Glad to help you! Your welcome!

It seems your topic is solved... Please set the status to resolved.. To do this:
Go to your first post ->
Edit your first post ->
Click "Go Advanced" ->
Then in the drop down next to the title, select "RESOLVED"

If you need an explanation:

The only reason example 4.3 works is because its testing string to string, your adding strings together.