我是JavaScript的新手,请原谅我的新意。但我现在正在运行此代码,以测试一些东西
var firstNumber = prompt("enter the first number ");
var secondNumber = prompt("enter the second number ");
var theTotal = firstNumber + secondNumber;
firstNumber = parseFloat(firstNumber);
secondNumber = parseFloat(secondNumber);
document.write(firstNumber + " added to " + secondNumber + " equals " + theTotal);
为什么不正确添加数字?我知道这样做的正确方法是将parseFloat包装在提示符周围,但我只是想知道为什么这不起作用。提前谢谢。
答案 0 :(得分:0)
firstNumber + secondNumber
正在添加strings
...尝试firstNumber*1 + secondNumber*1
将其快速转换为数字并查看结果。
答案 1 :(得分:0)
当你将firstNumber添加到secondNumber时,它们仍然是字符串;在添加之前,您不会将它们转换为数字。这样做:
firstNumber = parseFloat(firstNumber);
secondNumber = parseFloat(secondNumber);
var theTotal = firstNumber + secondNumber;
document.write(firstNumber + " added to " + secondNumber + " equals " + theTotal);