有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java int除法让我困惑

我做了非常简单的整数除法,得到了奇怪的结果

此代码按预期打印2

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

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

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

这是怎么回事

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


共 (3) 个答案

  1. # 1 楼答案

    0200是一个八进制值,十进制为128

    有关更多信息,请参阅Primitive Data Types说明的文字部分

  2. # 2 楼答案

    在这里观察到一个有趣的行为

    如果我做一个Integer.parseInt("0200"),我得到200作为o/p

    怎么了

  3. # 3 楼答案

    0200是一个八进制(基数8)常数。它等于128(十进制)

    Section 3.10.1 of the Java Language Specification

    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.