使用"f"后缀表示数字字面量

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

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行?

编辑:顺便问一下,这样做会有任何性能差异吗?

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;
// ...

谢谢,还有一个小问题。你知道那个吗? - Joan Venge
2
@Joan:我编辑了一下...顺便说一句,我的编辑操作要少得多 ;) - Reed Copsey
谢谢Reed。我同意,我也总是使用double。只是这个来自第三方库的代码让我感到困惑。 - Joan Venge
顺便问一下,“我的编辑还有更少的转换操作,是什么意思?”:哦,抱歉我没听懂那个笑话。 - Joan Venge

1

不会,结果是一样的。

如果你把1f改成1.0(或者1d),结果会是一个double


谢谢,还有一个小问题。你知道那个吗? - Joan Venge
2
@Joan:doublefloat操作的速度取决于CPU。 - SLaks
谢谢SLaks,那很有道理。 - Joan Venge

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接