对数字文字使用 f 后缀

问题描述 投票:0回答:2

我看到一些这样的代码:

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 行的第二个示例吗?

编辑:顺便说一句,会有什么性能差异吗?

c# .net math
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

© www.soinside.com 2019 - 2024. All rights reserved.