检查风向是否在指定范围内
我使用整数值(枚举)表示风向,范围从 0(北)到 15(北-西北-西)。
我需要检查给定的风向(0 到 15 之间的整数值)是否在一定范围内。我首先指定 WindDirectionFrom
值,顺时针移动到 WindDirectionTo
以指定允许的风向范围。
显然,如果 WindDirectionFrom=0
和 WindDirectionTo=4
(在 N 和 E 方向之间)并且风向为 NE (2),则计算很简单
int currentWindDirection = 2;
bool inRange = (WindDirectionFrom <= currentWindDirection && currentWindDirection <= WindDirectionTo);
//(0 <= 2 && 2 <= 4) simple enough...
但是对于不同的情况来说WindDirectionFrom=15
、WindDirectionTo=4
并且风向再次为 NE (2),计算立即中断...
bool inRange = (WindDirectionFrom <= currentWindDirection && currentWindDirection <= WindDirectionTo);
//(15 <= 2 && 2 <= 4) oops :(
我确信这不会太困难,但我对这个有一个真正的心理障碍。
I am representing wind directions using integer values (an Enum) ranging from 0 for North, through to 15 for North-North-West.
I need to check if a given wind direction (integer value between 0 and 15) is within a certain range. I specify my WindDirectionFrom
value first moving clockwise to WindDirectionTo
to specify the range of allowable wind direction.
Obviously if WindDirectionFrom=0
and WindDirectionTo=4
(between N and E direction) and the wind direction is NE (2) the calculation is simply
int currentWindDirection = 2;
bool inRange = (WindDirectionFrom <= currentWindDirection && currentWindDirection <= WindDirectionTo);
//(0 <= 2 && 2 <= 4) simple enough...
However for a different case where say WindDirectionFrom=15
, WindDirectionTo=4
and wind direction is NE (2) again, the calculation immediately breaks...
bool inRange = (WindDirectionFrom <= currentWindDirection && currentWindDirection <= WindDirectionTo);
//(15 <= 2 && 2 <= 4) oops :(
I'm sure this can't be too difficult, but I'm having a real mental block with this one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你想要的是模运算。进行模 16 算术,并检查差异是否至少为 14(-2 的模等价物)或最多 2。
如何进行模算术因语言而异。使用 C 或 C++,您会发现 x mod 16 如下:(
感谢 msw 指出,
enum
上的算术经常是不允许的,并且有充分的理由。enum
code> 通常表示离散且算术上不相关的对象或条件。)What you want is modular arithmetic. Do your arithmetic mod 16, and check to see if the difference is from (say) at least 14 (the modular equivalent of -2) or at most 2.
How to do modular arithmetic will vary between languages. With C or C++, you would find x mod 16 as follows:
(Thanks to msw for pointing out that arithmetic on
enum
s is frequently not allowed, and for good reasons. Anenum
normally represents objects or conditions that are discrete and not related arithmetically.)我会这样做:
I would do it like this: