Sum of two numbers with prompt

后端 未结 8 2481
甜味超标
甜味超标 2020-11-28 14:47

I\'ve been trying to solve this problem for the last couple days: when I subtract, multiply or divide 2 numbers input through a prompt, everything works fine; but when I wan

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 15:33

    The function prompt returns a string and + is (unwisely, perhaps) used for both string concatenation and number addition.

    You do not "specify types" in JavaScript but you can do string to number conversion at run time. There are many ways to so this. The simplest is:

    var a = +prompt("Enter first number");
    var b = +prompt("Enter second number");
    alert(a + b);
    

    but you can also do

    var a = Number(prompt("Enter first number"));
    var b = Number(prompt("Enter second number"));
    alert(a + b);
    

    (Avoid parseInt because it only handles the leading characters and will not add numbers like 4.5 and 2.6.)

提交回复
热议问题