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
How does Java store Negative numbers in an Integer Variable?
提问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
回答by Louis Wasserman
Numbers starting with 0
are treated as being in octal by Java. -077
is 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 开头时,它会将其解释为八进制格式