不知道如何使标题更具描述性,所以我只是从一个例子开始。我正在使用下面的代码位来选择一个枚举的方向,这取决于与给定方向相比,四个轴中的哪一个形成了最小的角度。根据N值中的哪一个返回不同的结果
static Direction VectorToDirection(Vector2 direction)
{
double upDiff = System.Math.Acos(Vector2.Dot(direction, -Vector2.UnitY));
double downDiff = System.Math.Acos(Vector2.Dot(direction, Vector2.UnitY));
double leftDiff = System.Math.Acos(Vector2.Dot(direction, -Vector2.UnitX));
double rightDiff = System.Math.Acos(Vector2.Dot(direction, Vector2.UnitX));
double smallest = System.Math.Min(System.Math.Min(upDiff, downDiff), System.Math.Min(leftDiff, rightDiff));
// This is the part I'm unsure about i.e.
// Comparing smallest with each value in turn
// To find out which of the four was "selected"
if (smallest == upDiff) return Direction.Up;
if (smallest == downDiff) return Direction.Down;
if (smallest == leftDiff) return Direction.Left;
return Direction.Right;
}
但我在最后得到关于浮点相等的resharper警告。我猜这不应该是一个问题,因为执行Min
,但想知道是否有更好的方式来解决这种问题除了比较smallest
与每个原始值。
谢谢你所有的答案,我有点不确定选择哪一个。对于像这样的一小部分值来说,像布兰登一样手动比较它们似乎是比我所做的更好的选择。对于一般情况,我喜欢阿列克谢的方法,通过索引找到最小值,并将其标记为更广泛的答案。 – 2012-08-06 18:55:16