使用f后缀表示数字文字

Joa*_*nge 3 .net c# compiler-construction math

我看到一些像这样的代码:

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;
Run Code Online (Sandbox Code Playgroud)

它是否像这样重要?:

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;
Run Code Online (Sandbox Code Playgroud)

编译器是否会使用(float) / (float)或尝试使用(double) / (float)第2行的第2个示例?

编辑:顺便说一下会有任何性能差异?

Ree*_*sey 6

它实际上(int)/(float)用于第二个例子.由于Int32可以隐式转换为Single,因此编译器不会抱怨,并且它可以正常工作.

话虽如此,如果你这样做,它会抱怨:

float num = 1.0 / ( ( float ) Math.Sqrt ( ( double ) num2 ) );
Run Code Online (Sandbox Code Playgroud)

这将导致它尝试使用(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;
// ...
Run Code Online (Sandbox Code Playgroud)

  • @Joan:我编辑过... BTW - 我的编辑也有很少的转换操作;) (2认同)