Java 为什么 int j = 012 给出输出 10?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23039871/
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
Why int j = 012 giving output 10?
提问by CoderCroc
In my actual project It happened accidentally here is my modified small program.
在我的实际项目中偶然发生的这里是我修改后的小程序。
I can't figure out why it is giving output 10?
我不明白为什么它给出输出10?
public class Int
{
public static void main(String args[])
{
int j=012;//accidentaly i put zero
System.out.println(j);// prints 10??
}
}
After that, I put two zeros still giving output 10.
在那之后,我放了两个零仍然给出输出 10。
Then I change 012 to 0123and now it is giving output 83?
然后我将012更改为 0123,现在它给出了输出 83?
Can anyone explain why?
谁能解释为什么?
采纳答案by Abimaran Kugathasan
Than I change 012 to 0123 and now it is giving output 83?
比我将 012 更改为 0123,现在它给出了输出 83?
Because, it's taken as octal base (8), since that numeral have 0 in leading. So, it's corresponding decimal value is 10
因为,它被视为八进制基数 (8),因为该数字的前导为 0。所以,它对应的十进制值为10
012 :
012 :
(2 * 8 ^ 0) + (1 * 8 ^ 1) = 10
0123 :
0123:
(3 * 8 ^ 0) + (2 * 8 ^ 1) + (1 * 8 ^ 2) = 83
回答by Mark
回答by user3463521
You are assigning a constant to a variable using an octal representation of an type int constant. So the compiler gets the integer value out of the octal representation 010 by converting it to the decimal representation using this algorithm 0*8^0 + 1+8^1 = 10 and then assign j to 10. Remember when you see a constant starting with 0 it's an integer in octal representation. i.e. 0111 is not 1 hundred and 11 but it's 1*8^0 + 1*8^1 + 1*8^2.
您正在使用 int 类型常量的八进制表示将常量分配给变量。因此,编译器通过使用此算法 0*8^0 + 1+8^1 = 10 将其转换为十进制表示,然后将 j 分配给 10,从而从八进制表示 010 中获取整数值。 0 是八进制表示的整数。即 0111 不是 100 11,而是 1*8^0 + 1*8^1 + 1*8^2。