2015-09-28 71 views
0

问题是:在控制台中显示什么?如何用''声明int,为什么是'2'== 50?

我真的有一些理解上的问题。

下面是代码:

public static void felda(){ 
    char[] felda = {'2',0x31,48}; 
    for (int i = 0; i< felda.length; i++){ 
     System.out.println(" : " + felda[i]); 
    } 
    System.out.println(); 
} 
public static void feldb(){ 
    int[] feldb = {'2',0x31,48}; 
    for (int i = 0; i< feldb.length; i++){ 
     System.out.println(" : " + feldb[i]); 
    } 
    System.out.println(); 
} 
public static void feldc(){ 
    int [] feldc = {'2',0x31,48}; 
    for (int i = 0; i< feldc.length; i++){ 
     System.out.println(" : " + (char) feldc[i]); 
    } 
    System.out.println(); 
} 

所以,如果我在解决方案上运行是:

: 2 
: 1 
: 0 

: 50 
: 49 
: 48 

: 2 
: 1 
: 0 

所以我不明白是怎么回事,甚至可能有“一个int definded ”。 我发现它很混乱如何int feldb = '2'结果是50和int feldb = 0x31结果是49 ..大坝这一切都很混乱。我希望有人能够启发我。

编辑:为什么char feldc = 48;导致0?

+1

HTTP://www.asciitable .com/ – QuakeCore

+1

http://www.ascii-code.com/ –

+0

相关:http://stackoverflow.com/questions/32051600/char-to-int-conversion –

回答

2

50是'2'字符的ASCII值。定义像它不是数字2 ..它给出一个字符的ASCII值。看到这个ASCII表,找到 '2' 字符

http://ascii.cl/index.htm?content=mobile

+0

从技术上讲,它没有给出字符的ASCII值,但是该字符的Unicode代码点。他们恰好是一样的。 –

4

在Java中,char代表一个Unicode字符。但它也实际上是一个无符号整数,2个字节,可以去从0到2 - 1

所以,

char c = '2'; 

初始化c字符 '2'。并且Unicode中字符'2'的数值为50.

因此,如果将其打印为字符,则会打印“2”。如果将其作为数值打印(作为int,使用int c = '2'),将打印50。

在做

char feldc = 48; 

初始化feldc与它的数字Unicode值是48字符,并且该字符是字符“0”。它是这样相当于

char feldc = '0'; 

0x31是(这是0x前缀的意思)写成一个十六进制文字的数字。当您编写31时,该值为十进制。它等于1 * 10 + 3 * 10 。

在十六进制中,碱是16而不是10。所以0x31等于1×16 + 3 * 16 ,它等于49。

相关问题