有 Java 编程相关的问题?

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

java 3*012=30,而不是36。为什么呢?

我很困惑这是为什么,我似乎找不到答案。这是作业中的内容:

x=1, y=2, z=3;

z=(int)(x/y*3.0+z*012);

System.out.printf("%d %d %d", x, y, z);

答案是:

1 2 30; << from eclipse

我是如何来到这里的:

(1/2) = 0 * 3.0 = 0 + (z*012)= 30。我想说36,但根据IDE,我猜是30


共 (4) 个答案

  1. # 1 楼答案

    在Java和其他几种语言中,以0开头的整数文本被解释为八进制(base 8)量。这里012是一个八进制数,它有一个十进制值f 10

    所以你的乘法会是这样的

    z = (int) (1/2 * 3.0 + 3 * 10);
    

    JLS

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

  2. # 2 楼答案

    012是一个八进制,因为它以0开头:

    012 = (0 * 8^2) + (1 * 8^1) + (2) = 10
    

    因此:

    012 * 3 = 10 * 3 = 30
    

    注意事项:

    • 记住,八进制是以8为基数的数字(十进制是以10为基数),所以它不能有大于或等于8的数字
    • 类似地,十六进制数以0x开头,例如:0x12 = 1*16 + 2 = 18
  3. # 3 楼答案

    JLS

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

    所以

    012=0*82+1*81+2*80=10

    在Java7中,可以使用underscores in numeric literals,这可能有助于中断值

  4. # 4 楼答案

    012是八进制数而不是十进制数,十进制值为10

    z=(int)(x/y*3.0+z*012);
    

    等于

    z=(int)(1/2*3.0+3*10);
    
    • 供参考

    以0开头的数字是八进制数
    以0x开头的数字是十六进制数
    数字以0b开头,或者OB是二进制数。(自Java第7版起)