PDA

View Full Version : Beginners help


lowcelnet
07-20-2003, 08:24 AM
I am learning Jscript I would appreciate a little help. I am performing a simple addition function but cannot get it to work. Script works with every operator except "+".

Please Help!! :confused: :confused: :confused: :confused:

<HTML>
<HEAD>
<SCRIPT language="javascript">
<!--
function calculate(a,b)
{
var a = prompt("Pick a number between 1 and 100?", "");
var b = prompt("Pick another number between 1 and 100?", "");
var c=a+b
var sum = "The sum of your entered integers are "
document.write( sum +c);
}
calculate();
//-->
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>

Philip M
07-20-2003, 09:00 AM
Your problem is that the + sign is concatenating the variables into a string, not summing them. JavaScipt is a loosely typed language so variables can store numbers, text strings or Boolean values without any distinction.

An easy solution to this is:-


var c=(a*1)+(b*1);
var sum = "The sum of your entered integers is ";
document.write( sum + c);


Or you could initialise a and b as numbers:

var a = 0;
var b = 0;


But there is nothing in your script to require integer numbers only being input, and the result is correct for real (decimal) numbers as well.

So you could use:-

a=parseInt(a);
b=parseInt(b);
var c=a+b

As a tip, it is not a very good idea to use the variable name "sum" for a string message, as sensibly "sum" is the variable name of the result of the addtion (c in your instance). Variable names such as a and b give no clue as to what they represent and can be difficult to guess. Far better is to use an indicative name such as "firstnum" and "secondnum", with "sum" being the result. What you call "sum" might be something like "message1".

lowcelnet
07-20-2003, 09:14 AM
I tried your advice and it definetly worked. Thanks so much for you help. You have virtually built the next step in my jscript progress.