[英]Use of trailing characters in JAVA/C++
我很好奇我們為什么在Java / C ++中使用結尾字符。 喜歡,
float f = 23f;
我們也可以寫
float f = 23;
兩者具有相同的效果。
在數學運算中對數字進行硬編碼時,這一點很重要。
例如:
5 / 2 == 2
5.0f / 2.0f = 2.5f
5.0 / 2.0 = 2.5 // without the 'f' suffix you have doubles
5.0d / 2.0d = 2.5d // for doubles 'd' can be used as well
這些也會有不同的結果:
blah / 3.141592653592 // this returns an accurate double
blah / 3.141592653592f // this returns a less accurate float
這是因為在第二種情況下,還有其他東西可以提供類型信息(即變量的類型)。 在這種情況下,不需要后綴。
但是,在其他情況下,當類型信息必須從數字文字本身派生時,可能需要它們。 例如,考慮以下兩個表達式:
float f = 23 / 5; // Integer division
與
float f = 23f / 5; // Floating point division
帶或不帶后綴,您將獲得不同的結果。
它們具有相同的效果,但是第二個步驟又需要額外的步驟。 數據類型23
是int
。 編譯器幾乎可以肯定在編譯時將23
轉換為浮點數,但是它確實必須檢查數字是否可以表示為浮點數。 它們占用相同的空間,因此某些整數不能表示為浮點數。 考慮以下Java代碼:
int i = 2147483647; // Integer.MAX_VALUE, but at compile time.
System.out.println(i);
float f = 2147483647; // Integer.MAX_VALUE, but at compile time.
System.out.println(f);
打印什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.