Java 如何在整数变量中存储负数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32831145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 13:10:18  来源:igfitidea点击:

How does Java store Negative numbers in an Integer Variable?

java

提问by Ashish Krishnan

How does this snippet of code prints "-511" as the output on the console?

这段代码如何在控制台上打印“-511”作为输出?

   class Test
   {
    public static void main(String[] args) {
    int i = -0777; 
    System.out.printf("%d",i);
    }
   }

Is it to do with the way Java stores Negative numbers?

是否与 Java 存储负数的方式有关?

采纳答案by ouah

Integer numbers prefixed with 0are octalnumbers. To use decimal numbers remove the 0prefix:

带前缀的整数0八进制数。要使用十进制数字,请删除0前缀:

int i = -777;

回答by Louis Wasserman

Numbers starting with 0are treated as being in octal by Java. -077is equivalent to -63, which is what I get when I run your program.

以 开头的数字0被 Java 视为八进制。 -077相当于-63,这是我运行您的程序时得到的结果。

回答by ControlAltDel

When a number in java code starts with a 0, it interprets it as octal format

当 java 代码中的数字以 0 开头时,它会将其解释为八进制格式