Java int 部门让我感到困惑

2022-01-14 00:00:00 division int octal java

我正在做非常简单的 int 除法,结果很奇怪.

I am doing very simple int division and I am getting odd results.

此代码按预期打印 2:

public static void main(String[] args) {
    int i = 200;
    int hundNum = i / 100;
    System.out.println(hundNum);
}

此代码将 1 打印为 not 预期:

This code prints 1 as not expected:

public static void main(String[] args) {
    int i = 0200;
    int hundNum = i / 100;
    System.out.println(hundNum);
}

这是怎么回事?

(Windows XP Pro,Java 1.6 在 Eclipse 3.4.1 中运行)

推荐答案

0200 是一个 八进制 (base 8) 常量.它等于 128(十进制).

The value 0200 is an octal (base 8) constant. It is equal to 128 (decimal).

来自 第 3.10.1 节Java 语言规范:

八进制数字由一个 ASCII 数字 0 后跟一个或多个 ASCII 数字 0 到 7 组成,可以表示正整数、零整数或负整数.

An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 and can represent a positive, zero, or negative integer.

相关文章