前面有零的整数是什么意思,我该如何打印它?
What does an integer that has zero in front of it mean and how can I print it?
class test{
public static void main(String args[]){
int a = 011;
System.out.println(a);
}
}
为什么我的输出是 9
而不是 011
?
如何获得 011
作为输出?
以 0 开头的数字文字被解析为八进制数(即基数 8)。 011是八进制的9.
011
被解释为八进制数。这意味着它以 8 为基数。另请参阅 this SO post。来自 Stuart Cook 接受的答案:
In Java and several other languages, an integer literal beginning with 0 is interpreted as an octal (base 8) quantity.
以 10 为基数的数字:
100 秒、10 秒、1 秒
8 进制的数字:
64 秒、8 秒、1 秒
所以 011
被解释为 8+1=9
JLS 3.10.1描述了 4 种定义整数的方法。
An integer literal may be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2).
An octal numeral consists of a digit 0 followed by one or more of the digits 0 through 7 ...
A decimal numeral is either the single digit 0, representing the integer zero, or consists of an digit from 1 to 9 optionally followed by one or more digits from 0 to 9 ...
总而言之,如果您的整数文字(即 011
)以 0 开头,那么 java 将假定它是一个 octal notation。
解决方案:
如果您希望您的整数保留值 11,那么不要幻想,只需分配 11。毕竟,该表示法不会更改值的任何内容。我的意思是,从数学的角度来看 11 = 011 = 11,0.
int a = 11;
格式仅在打印时(或将 int
转换为 String
时才重要)。
String with3digits = String.format("%03d", a);
System.out.println(with3digits);
格式化程序"%03d"
用于添加前导零。
或者,您可以使用 printf
方法在 1 行中完成。
System.out.printf("%03d", a);
class test{
public static void main(String args[]){
int a = 011;
System.out.println(a);
}
}
为什么我的输出是 9
而不是 011
?
如何获得 011
作为输出?
以 0 开头的数字文字被解析为八进制数(即基数 8)。 011是八进制的9.
011
被解释为八进制数。这意味着它以 8 为基数。另请参阅 this SO post。来自 Stuart Cook 接受的答案:
In Java and several other languages, an integer literal beginning with 0 is interpreted as an octal (base 8) quantity.
以 10 为基数的数字:
100 秒、10 秒、1 秒
8 进制的数字:
64 秒、8 秒、1 秒
所以 011
被解释为 8+1=9
JLS 3.10.1描述了 4 种定义整数的方法。
An integer literal may be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2).
An octal numeral consists of a digit 0 followed by one or more of the digits 0 through 7 ...
A decimal numeral is either the single digit 0, representing the integer zero, or consists of an digit from 1 to 9 optionally followed by one or more digits from 0 to 9 ...
总而言之,如果您的整数文字(即 011
)以 0 开头,那么 java 将假定它是一个 octal notation。
解决方案:
如果您希望您的整数保留值 11,那么不要幻想,只需分配 11。毕竟,该表示法不会更改值的任何内容。我的意思是,从数学的角度来看 11 = 011 = 11,0.
int a = 11;
格式仅在打印时(或将 int
转换为 String
时才重要)。
String with3digits = String.format("%03d", a);
System.out.println(with3digits);
格式化程序"%03d"
用于添加前导零。
或者,您可以使用 printf
方法在 1 行中完成。
System.out.printf("%03d", a);