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.
例子:如果我把 5 和 6 相加,我得到 56!!
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);
我做错了什么?我必须指定值类型吗?
What am I doing wrong? Do I have to specify the value type?
推荐答案
prompt
函数返回一个字符串,+
(可能是不明智的)用于 字符串连接和数字加法.
The function prompt
returns a string and +
is (unwisely, perhaps) used for both string concatenation and number addition.
您无需在 JavaScript 中指定类型",但您可以在运行时进行字符串到数字的转换.有很多方法可以做到这一点.最简单的是:
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);
但你也可以这样做
var a = Number(prompt("Enter first number"));
var b = Number(prompt("Enter second number"));
alert(a + b);
(避免使用 parseInt
,因为它只处理前导字符,不会添加像 4.5 和 2.6 这样的数字.)
(Avoid parseInt
because it only handles the leading characters and will not add numbers like 4.5 and 2.6.)
这篇关于带提示的两个数字之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带提示的两个数字之和


基础教程推荐
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01