本文介绍了用Java中的char变量进行计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有一个学校的作业,任务之一是解释很多微小的计算,并解释为什么java给您输出它给您的输出.

I have an assignment for school, and one of the tasks is to explain a lot of tiny calculations and explaining why java gives you the output it gives you..

其中一项计算是:

1 +'2'+ 3

1 + '2' + 3

这对我来说是一个词汇错误,因为老师在我的系统上使用了错误的撇号",但是我与其他同学交谈,他们告诉我他们得到了实际的输出,因此我开始阅读它,并发现它应该表示一个char变量,并且我还了解了系统特定的类型,因此我更改了符号以使其适用于我的系统,现在我得到了答案 54 .

which for me gives a lexical error, as the teacher used the wrong "apostrophes" for my system, but I've talked to other fellow students and they told me they got an actual output, so I started reading about it, and found out that it is supposed to signify a char variable, and I also found out about the system specific types, so I changed the signs to work for my system, and now I get the answer 54..

我看不到其中的逻辑,我尝试用char变量在Google中进行添加/计算/数学运算,但没有找到任何能很好解释它的方法.

and I cannot see the logic in it, and I've tried to google adding/calculating/math with char variables, and have found nothing that explains it well..

因此,我向编码人员求助,希望有一天我可以成为帮助我了解其逻辑的一部分.

So I turn to you, the people of coding, that I one day might be a part of to help me understand the logic of this..

这最初是作为一项家庭作业,我可能只是通过回答它会给出一个词法错误来解决,因为我的编译器不理解该符号,但是现在它使我的好奇心达到了顶峰,我真的想知道如何java设法得到了这个答案.

this started out as a homework assignment that I probably could have gotten through by just answering that it gives a lexical error because my compiler doesn't understand the symbol, but now it's peaked my curiosity, and I really want to know how java manages to get this answer..

感谢您对此事的任何帮助! :)

thank you for any help on the matter! :)

我可以看到我无法制作作业"标签,所以我希望可以将其放在这里:)

I can see that I couldn't make a 'homework' tag, so I hope it's okay that I put it here :)

推荐答案

在Java中,char通过UTF-16直接映射到int.但是,对于大多数常见字符,将char值转换为int会在ascii表上产生其索引. +不是对char的运算,但是它是对int的运算.因此,java使用了2,并在考虑了我不能添加此内容"之后,意识到将其强制转换为int即可添加.

In Java, chars have a direct mapping to ints by UTF-16. For most common characters, though, casting a char value to an int yields its index on the ascii table. + isn't an operation on chars, but it is an operation for ints. Therefore, java is taking the 2 and after thinking "I can't add this", realizes it can add it if it casts it to an int.

如表所示,'2'的索引为50,因此1 + 50 + 3 = 54.

As you can see in the table, '2' has a index of 50, thus 1 + 50 + 3 = 54.

这篇关于用Java中的char变量进行计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 15:19