+ 7
It is resulting as string . Like 4+2=42 . How to make it 4+2=6.
when I changed the code to ask for input, instead of returning 42 it'd return 402. (or instead of 1+1=2 it'd return 1+1=11) var a = prompt(); var b = prompt(); function addNumbers(a, b) { var c = a+b; return c; } document.write( addNumbers(a, b) );
9 odpowiedzi
+ 6
var c = Number(a)+Number(b);
+ 7
Additionally, Number() returns NaN (Not a Number) when either <a> or <b> as its argument were not convertible to a number.
It might worth to consider checking that neither Number( a ) nor Number( b ) was NaN, before adding the two.
a = Number( a );
b = Number( b );
if( !isNaN( a ) && !isNaN( b ) )
{
return a + b;
}
return 0;
+ 2
makhrab dip
When you takes user input it returns as a string so 4 and 2 are string.
try this:
var a = prompt();
console.log(typeof a)
so either you can write Number(prompt()) or you can write parseInt(prompt(), 10)
var a = parseInt(prompt(), 10);
var b = parseInt(prompt(), 10);
console.log(a + b);
+ 1
You can also convert to a number by using the following...
var c = parseInt(a) + parseInt (b);
+ 1
var a = prompt();
var b = prompt();
var c = +a + +b;
document.write(c);
If you prepend var a and b with + sign this will work also.
0
By default the input are string. So they are just concatenated when added. Convert them to numbers to add.
return Number(a) + Number(b)
0
Use TryParse to check for int then add.
0
Var c = prompt(a+b)