我尝试在Javascript中添加两个数字:
var output;
output = parseInt(a)+parseInt(b);
alert(output);
它提供了错误的output
值,例如如果a = 015
和b = 05
。为什么会这样?
上述例子的预期结果应为20。
答案 0 :(得分:7)
如果您使用0
为数字添加前缀,则在基数8中指定它们。015
因此为13,总和为18。
使用第二个parseInt
参数强制基数:
var a = '015', b = '05';
var output;
output = parseInt(a, 10) + parseInt(b, 10);
alert(output); // alerts 20
答案 1 :(得分:0)
在许多编程语言中,以前导0开头的数字表示数字的基数8(八进制)表示。在这里你给八进制数作为输入并期望输出十进制,这就是你说输出错误的原因(这是正确的!wrt octal加法)
solution 1 : you can add two octal numbers and convert the result to decimal
solution 2 : convert the octal numbers to decimal and then add them