2015-12-23 18 views
7

我使用的XCode點符號在迅速

正好與此表達發生什麼通過https://github.com/nettlep/learn-swift第一基本遊樂場工作p表示十六進制數字文字?

0xC.3p0 == 12.1875 

我瞭解十六進制文字和特殊的「P」符號表示的2

0xF == 15 

0xFp0 == 15 // 15 * 2^0 

電源如果我嘗試0xC.3我得到的錯誤:十六進制浮點文字必須結束與指數。

我發現這個不錯overview of numeric literalsanother deep explanation,但我沒有看到解釋什麼.3p0做什麼。

我分叉了代碼並將本課升級到了XCode 7/Swift 2 - 這裏是specific line

回答

5

這是Hexadecimal exponential notation

By convention, the letter P (or p, for "power") represents times two raised to the power of ... The number after the P is decimal and represents the binary exponent.

...

Example: 1.3DEp42 represents hex(1.3DE) × dec(2^42).

對於你的榜樣,我們得到:

0xC.3p0 represents 0xC.3 * 2^0 = 0xC.3 * 1 = hex(C.3) = 12.1875 

where hex(C.3) = dec(12.{3/16}) = dec(12.1875) 

舉個例子,你可以嘗試0xC.3p1(等於hex(C.3) * dec(2^1)),這將產生雙重價值,即24.375

您也可以研究在操場二進制指數增長的十六進制值1:

// ... 
print(0x1p-3) // 1/8 (0.125) 
print(0x1p-2) // 1/4 (0.25) 
print(0x1p-1) // 1/2 (0.5) 
print(0x1p1) // 2.0 
print(0x1p2) // 4.0 
print(0x1p3) // 8.0 
// ... 

最後,這也是Apple`s Language Reference - Lexical Types: Floating-Point Literals解釋說:

Hexadecimal floating-point literals consist of a 0x prefix, followed by an optional hexadecimal fraction, followed by a hexadecimal exponent. The hexadecimal fraction consists of a decimal point followed by a sequence of hexadecimal digits. The exponent consists of an upper- or lowercase p prefix followed by a sequence of decimal digits that indicates what power of 2 the value preceding the p is multiplied by. For example, 0xFp2 represents 15 x 2^2, which evaluates to 60. Similarly, 0xFp-2 represents 15 x 2^-2, which evaluates to 3.75.

+0

感謝詳細說明。扔掉我的東西是0xC.3是不允許的,這使我不能識別它爲十六進制分數。鑑於Apple參考文獻中的語法,似乎這個錯誤可能是一個錯誤? – Ultrasaurus

+0

@Ultrasaurus不客氣。我可以看到這是如何拋棄你的,如果你使用十六進制數字而不是十六進制數字,這可能會有點奇怪。指數表示法。我想說,錯誤是預期的行爲,但是,正如文檔(上面)指出的那樣*「...由0x前綴組成,後面跟着一個可選的十六進制小數,後面跟着一個十六進制指數。即,十六進制指數需要以十六進制格式存在於完整的浮點文字中。 ... dfri

+0

...從文檔中,查找*「浮點文字的語法」下的*「浮點文字」* *:如果我們要使用十六進制符號,浮點必須在窗體上呈現*十六進制文字可選(十六進制小數)十六進制指數*。後者* hex-exp *對於此表示是強制性的;因此排除它會導致編譯時錯誤。 – dfri