【发布时间】:2010-01-15 00:42:41
【问题描述】:
我有一个 C# 中的向量类(下面的片段)。我的问题是,当我调用 GetMagnitude() 时,它总是返回 0.0f - 即使调试器正在运行并且我检查 Sq 是否具有有效值,只要它被传递回其他函数(例如: Normalize() ),它返回 0.0f。有人可以解释一下并帮我解决吗?我的猜测是它与 double->float 转换有关,但我就是想不通。
public class float3
{
public float x;
public float y;
public float z;
public float GetMagnitude()
{
float SumSquares = (float)( Math.Pow(x, 2) + Math.Pow(y, 2) + Math.Pow(z, 2));
float Sq = (float)Math.Sqrt(SumSquares);
return Sq;
}
public void Normalize()
{
float inverse = 1.0f / GetMagnitude();
x *= inverse;
y *= inverse;
z *= inverse;
}
}
【问题讨论】:
-
你有没有初始化过 x、y 和 z?在您的示例中,它显然会返回 0。
-
您可能要考虑编写 xx + yy + z*z 而不是使用 Math.Pow...它既短又快...跨度>
标签: c# vector casting floating-point double