"几乎可以分割"

bob*_*obo 12 numbers modulo visual-c++

我想检查一个浮点值是否"几乎"是32的倍数.例如64.1"几乎"可被32整除,因此是63.9.

现在我这样做:

#define NEARLY_DIVISIBLE 0.1f
float offset = fmodf( val, 32.0f ) ;
if( offset < NEARLY_DIVISIBLE )
{
    // its near from above
}
// if it was 63.9, then the remainder would be large, so add some then and check again
else if( fmodf( val + 2*NEARLY_DIVISIBLE, 32.0f ) < NEARLY_DIVISIBLE )
{
    // its near from below
}
Run Code Online (Sandbox Code Playgroud)

有更好的方法来做到这一点?

fas*_*ion 3

好吧,你可以通过再次减去 32 来删除第二个 fmodf 以获得下面的 mod。

  if( offset < NEARLY_DIVISIBLE )
   {
       // it's near from above
   }
   else if( offset-32.0f>-1*NEARLY_DIVISIBLE)
   {
       // it's near from below
   }
Run Code Online (Sandbox Code Playgroud)

  • 或: else if (32.0f - 偏移量 &lt; NEARLY_DIVISIBLE); (2认同)