【问题标题】:Check if wind direction is within a specified range检查风向是否在指定范围内
【发布时间】:2010-07-21 20:40:38
【问题描述】:

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

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

【问题讨论】:

    标签: language-agnostic enums discrete-mathematics


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 啊,好吧,我使用的是 C#,所以我想它的语法和你在这里的几乎一样。
    • 正确,除了许多语言不允许对枚举进行算术运算(有充分的理由)。 OP 必须将他的枚举转换为数字。
    【解决方案2】:

    我会这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2017-07-13
      • 2022-11-15
      • 1970-01-01
      • 2021-03-30
      • 2016-05-03
      相关资源
      最近更新 更多