Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

javascript - Sum of two numbers with prompt

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 want to add them, I get the 2 numbers simply written together.

Example: if I add 5 and 6, I get 56!!

Here's the code I'm working with.

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

alert(a + b);
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...