Вопрос

Possible Duplicate:
why is initializing an integer in VC++ to 010 different from initialising it to 10?

This got me very confused, and I hope one of you can answer my question. How come this code will produce the output "116"?

#include <iostream>

int main()
{
    std::cout << 0164 << std::endl;
    return 0;
}

The code has been compiled with MSVC++ 2010 and g++ under Mac OS X. "cout" can print '0' alone and '164' alone, but as soon '0' is the first digit in the number the output changes.

Это было полезно?

Решение

Because the 0 in front makes the number be interpreted as octal.

0164 = 
 4 * 1 +
 6 * 8 + 
 1 * 64
 = 116

Or, via binary:

 0164 =
   0   1   6   4 = 
 000 001 110 100 =
 1110100 = 
 116

The same goes for hexadecimal numbers, you write them as 0x1FA for example.

Другие советы

In C and its brethren, a number with 0 on the front is octal, not decimal.

Hence your number is 1 * 82 (1 * 64 = 64) plus 6 * 81 (6 * 8 = 48) plus 4 * 80 (4 * 1 = 4) which equates to 116.

See here for a large treatise on what hexadecimal and octal are in C.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top