0

我使用整数值(枚举)表示风向,范围从 0 代表北,到 15 代表北-北-西。

我需要检查给定的风向(0 到 15 之间的整数值)是否在一定范围内。我指定我的WindDirectionFrom值首先顺时针移动WindDirectionTo以指定允许的风向范围。

显然,如果WindDirectionFrom=0WindDirectionTo=4(在 N 和 E 方向之间)且风向为 NE (2) 计算很简单

int currentWindDirection = 2;
bool inRange = (WindDirectionFrom <= currentWindDirection && currentWindDirection <= WindDirectionTo); 
              //(0 <= 2 && 2 <= 4) simple enough...

然而,对于另一种情况,比如WindDirectionFrom=15WindDirectionTo=4并且风向再次为 NE (2),计算立即中断......

bool inRange = (WindDirectionFrom <= currentWindDirection && currentWindDirection <= WindDirectionTo); 
              //(15 <= 2 && 2 <= 4) oops :(

我敢肯定这不会太难,但我对这个有一个真正的心理障碍。

4

2 回答 2

2

你想要的是模运算。做你的算术模型 16,并检查差异是否来自(例如)至少 14(模等效 -2)或最多 2。

如何进行模运算将因语言而异。使用 C 或 C++,您会发现 x mod 16 如下:

int xm = x % 16;
if (xm < 0) xm += 16;

(感谢 msw 指出enum经常不允许对 s 进行算术运算,这是有充分理由的。Anenum通常表示离散且在算术上不相关的对象或条件。)

于 2010-07-21T20:47:48.503 回答
1

我会这样做:

int normedDirection( int direction, int norm )
{
   return (NumberOfDirections + currentDirection - norm) % NumberOfDirections;
}

int normed = normedDirection( currentWindDirection, WindDirectionFrom );
bool inRange = (0 <= normed && normed <= normedDirection( WindDirectionTo, WindDirectionFrom ); 
于 2010-07-21T20:58:45.597 回答