Jump to content

[SOLVED] noob question regading varibles


JamesThePanda

Recommended Posts

hi guys

Im realy new to learning jscript

basically I want to make a litle script with 2 propts asking for 2 numbers and the it adds them both together

 

the script I made is as follows

 

<script type="text/javascript">


function add(a,b)
{
x=a+b;
return x;
}

var num1=prompt("what is number a?");
var num2=prompt("what is number b?");

alert(add(num1,num2));

</script>

I entered 1 for both the number and the ouput comes out as 11
can someone point out were im going wrong. I wanted the out put to be 2

thanks

james

Link to comment
Share on other sites

The reason it is doing that is because you are adding 2 strings together. You need to convert those strings to integers. Try this:

 

<script type="text/javascript">


function add(a,b)
{
x=parseInt(a)+parseInt(b);
return x;
}

var num1=prompt("what is number a?");
var num2=prompt("what is number b?");

alert(add(num1,num2));

</script>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.