首页 > 解决方案 > Why is 02000 evaluated to 1024

问题描述

Out of curiosity, I wrote a program like this:

auto number1 = 100;
auto number2 = 02000;
auto number3 = 2;

auto result = (number1 + number2) / number3;

std::cout << result;

Interestingly, the program outputs 562. So, in visual studio, i hovered over the variable "number2" and it showed (int) 1024. I didn't understand why this happened. So, I tried its equivalent in php which was this:

$number1 = 100;
$number2 = 02000;
$number3 = 2;

$result = ($number1 + $number2) / $number3;

echo $result;

The result was the same 562. What is it that I am missing because if I remove the zero in front of number2 to make it '2000', it shows 1050 as expected

标签: phpc++zeroarithmetic-expressions

解决方案


It treats 02000 as octal number and converts to decimal. Anythings that starts with preceding 0 is considered octal number.

0 2 0 0 0 = 0*8*8*8*8 + 2*8*8*8 + 0*8*8 + 0*8 + 0
          = 0 + 2*512 + 0 + 0 + 0
          = 1024

Now 1024 is number2.

result = (100 + 1024)/2
       = 1124/2
       = 562

推荐阅读