2011-01-19 33 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