2010-07-21 57 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