如何使用提示(如简单的计算器)对数字求和? [英] How do I sum numbers using a prompt, like a simple calculator?
问题描述
我试图使用JavaScript(百分比计算器)来做一件非常简单的事情。这是代码:
var num =提示(数字是多少?)
var perc =提示(变化百分比是多少?)
var math = num /(perc + 100)* 100
var result = alert(eval(math))
但是,由于某些原因,我可以总结一下,例如:
var num1 = 15
var num2 = 100
警报(num1 + num2)
它将显示115,但是我无法使用类似这样的值求和:
var num1 =提示(输入数字。)
var num2 = 100
警报(num1 + num2)
如果我在num1中写入15,则警报将显示15100。我尝试了一些操作,但没有任何操作,因此我确实需要这方面的帮助。
您无法使用,因为它有效地执行了 15 + 100 = 15100
,因为提示符返回了一个字符串。 / p>
您需要使用 parseInt
var num1 = parseInt(prompt( Input a number。),10)// 10对于十进制
var num2 = 100
alert(num1 + num2)
I tried to do a REALLY simple thing using JavaScript, a percentage calculator. This is the code:
var num = prompt("What is the number?")
var perc = prompt("What is the percentage of change?")
var math = num / (perc + 100) * 100
var result = alert(eval(math))
But, for some reason, I can sum, for example:
var num1 = 15
var num2 = 100
alert(num1 + num2)
It will display 115, but I can't sum using something like this:
var num1 = prompt("Input a number.")
var num2 = 100
alert(num1 + num2)
If I write 15 in num1, the alert will display 15100. I tried some things, but none of them worked, so I really need help on this.
Yours doesn't work because it's effectively doing "15" + 100 = 15100
because prompt returns a string.
You need to cast it from a string to a number using parseInt
var num1 = parseInt(prompt("Input a number."), 10) //10 for decimal
var num2 = 100
alert(num1 + num2)
这篇关于如何使用提示(如简单的计算器)对数字求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!