为什么我的比较在 Java 中的 char 和 int 之间不起作用? [英] Why doesn't my compare work between char and int in Java?
问题描述
char c = '0';
int i = 0;
System.out.println(c == i);
为什么这总是返回 false?
Why does this always returns false?
推荐答案
虽然这个问题很不清楚,但我很确定发帖人想知道为什么会打印false
:
Although this question is very unclear, I am pretty sure the poster wants to know why this prints false
:
char c = '0';
int i = 0;
System.out.println(c == i);
答案是因为每个可打印的字符都分配了一个唯一的代码编号,这就是 char
在被视为 int
时所具有的值.字符0
的码号是十进制的48,显然48不等于0.
The answer is because every printable character is assigned a unique code number, and that's the value that a char
has when treated as an int
. The code number for the character 0
is decimal 48, and obviously 48 is not equal to 0.
为什么数字的字符代码不等于数字本身?主要是因为前几个代码,尤其是 0
,太特殊了,不能用于如此平凡的目的.
Why aren't the character codes for the digits equal to the digits themselves? Mostly because the first few codes, especially 0
, are too special to be used for such a mundane purpose.
这篇关于为什么我的比较在 Java 中的 char 和 int 之间不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!