前缀零改变数字加法中的输出

Prefix zero changes output in number addition

本文关键字:输出 改变 数字 前缀      更新时间:2023-09-26

我试图在Javascript中添加两个数字:

 var output;
 output = parseInt(a)+parseInt(b);
 alert(output);

它给出了错误的output值,例如如果a = 015b = 05。为什么会这样?上述示例的预期结果应该是20。

如果在数字前面加上0,则以8为基数指定数字。因此015是13,并且总和是18。

使用第二个parseInt参数强制一个基数:

var a = '015', b = '05';
var output;
output = parseInt(a, 10) + parseInt(b, 10);
alert(output); // alerts 20

在许多编程语言中,以0开头的数字表示数字的基数8(八进制)。这里你给出的是八进制数字作为输入,并期望输出为十进制,这就是你说输出错误的原因(这是正确的!!wrt八进制加法)

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