2011-01-19 31 views
3

我看到一些這樣的代碼:的數字文字使用後綴f

float num2 = ((this.X * this.X) + (this.Y * this.Y)) + (this.Z * this.Z); 
float num = 1f/((float) Math.Sqrt ((double) num2)); 
this.X *= num; 
this.Y *= num; 
this.Z *= num; 

不要緊,如果是這樣的?:

float num2 = ((this.X * this.X) + (this.Y * this.Y)) + (this.Z * this.Z); 
float num = 1/((float) Math.Sqrt ((double) num2)); 
this.X *= num; 
this.Y *= num; 
this.Z *= num; 

請問編譯器使用(float)/(float)或嘗試使用(double)/(float)對於第2行的第二個例子?

編輯:順便說一句會有任何性能差異?

回答

6

對於第二個例子,它實際上使用(int)/(float)。由於Int32可以隱式轉換爲Single,所以編譯器不會抱怨,並且它可以正常工作。

話雖這麼說,如果你這樣做,它會抱怨:

float num = 1.0/((float) Math.Sqrt ((double) num2)); 

這將導致它嘗試使用(double)/(float),這將有效地變成(double)/(double)。當double試圖隱式設置爲float變量時,編譯器會發出抱怨。


編輯:順便說一下會有任何性能差異?

可能不是一個可測量的。話雖如此,你將在IL中創建額外的轉換操作。這些可能會在JIT期間被淘汰 - 但同樣,它將是微觀的。

就個人而言,我可能會處理這個使用雙精度數學,因爲它使代碼更易於閱讀:

double num2 = (this.X * this.X) + (this.Y * this.Y) + (this.Z * this.Z); 
float num = (float) (1.0/Math.Sqrt(num2)); 
this.X *= num; 
// ... 
1

否;它會是一樣的。

如果將1f更改爲1.0(或1d),則結果爲double

+0

謝謝,還增加了一個小問題。你知道那個嗎? – 2011-01-19 21:37:53

+2

@Joan:'double'與'float'操作的速度取決於CPU。 – SLaks 2011-01-19 21:46:36