Language agnostic 检查风向是否在规定范围内

Language agnostic 检查风向是否在规定范围内,language-agnostic,enums,discrete-mathematics,Language Agnostic,Enums,Discrete Mathematics,我用整数值(一个枚举)表示风向,范围从北0到西北15 我需要检查给定的风向(0到15之间的整数值)是否在一定范围内。我指定我的WindDirectionFrom值,首先顺时针移动到WindDirectionTo,以指定允许的风向范围 显然,如果WindDirectionFrom=0和WindDirectionTo=4(在N和E方向之间),且风向为NE(2),则计算简单 int currentWindDirection = 2; bool inRange = (WindDirectionFrom

我用整数值(一个枚举)表示风向,范围从北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...

我相信这不会太难,但我对这一点有一个真正的心理障碍。

你想要的是模运算。做你的算术mod 16,检查差异是否来自(比如)至少14(模化等价物-2)或最多2

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

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

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

您需要的是模运算。做你的算术mod 16,检查差异是否来自(比如)至少14(模化等价物-2)或最多2

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

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

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

我会这样做:

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

int normed = normedDirection( currentWindDirection, WindDirectionFrom );
bool inRange = (0 <= normed && normed <= normedDirection( WindDirectionTo, WindDirectionFrom ); 
int-normedDirection(int-direction,int-norm)
{
返回(NumberOfDirections+currentDirection-norm)%NumberOfDirections;
}
int normed=normedDirection(currentWindDirection,WindDirectionFrom);

bool inRange=(0我会这样做:

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

int normed = normedDirection( currentWindDirection, WindDirectionFrom );
bool inRange = (0 <= normed && normed <= normedDirection( WindDirectionTo, WindDirectionFrom ); 
int-normedDirection(int-direction,int-norm)
{
返回(NumberOfDirections+currentDirection-norm)%NumberOfDirections;
}
int normed=normedDirection(currentWindDirection,WindDirectionFrom);

bool inRange=(0啊,对了,我使用的是C#,所以我猜它的语法将与您在这里得到的语法几乎相同。正确,除了许多语言不允许枚举上的算术(有充分的理由)。OP必须将他的枚举数转换成数字。啊,对了,我使用的是C,所以我猜它的语法将与您在这里使用的语法几乎相同。正确,除了许多语言不允许枚举数上的算术(有充分的理由)。OP必须将他的枚举数转换成数字。