不知道如何使标题更具描述性,所以我将从一个示例开始。我正在使用下面的代码位,它从枚举中选择一个方向,具体取决于与给定方向相比,四个轴中的哪个轴形成的角度最小。
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