2010-07-21 61 views
0

我使用整数值(一个Enum)表示风向,范围从北到北从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 :(

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

回答

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); 
2

你想要的是模块化算术。做你的算术mod 16,然后检查差异是否来自(比方说)至少14(模数等于-2)或最多2.

如何进行模块化运算会因语言而异。用C或C++,你会发现在x mod 16如下:

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

(感谢MSW为指出,在enum小号算术经常不允许的,并有很好的理由的enum通常代表对象或条件。这是离散的,而不是算术相关的)

+0

啊哈吧,还有我使用C#,所以我想这将是几乎相同的语法,你”我已经到了这里。 – 2010-07-21 20:50:33

+0

正确,除了很多语言不允许算术枚举(出于很好的理由)。 OP将不得不将他的枚举变成数字。 – msw 2010-07-21 20:50:43