問題描述
我有一個學校作業,其中一項任務是解釋許多微小的計算,并解釋為什么 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
s 可以通過 UTF-16 直接映射到 int
s.但是,對于大多數常見字符,將 char
值轉換為 int
會在 ascii 表中生成它的索引.+
不是對字符的操作,而是對整數的操作.因此,java 采用 2
并在思考我無法添加這個"之后,意識到如果將其強制轉換為 int,它可以添加它.
In Java, char
s have a direct mapping to int
s 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變量計算的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!