floor()/ int()函数实现

Olg*_*lga 5 implementation function

有没有人有一个想法如何在方法/功能Int()floor()实施?我正在寻找各自的实现,因为以下是abs()功能.

Int Abs (float x){
  if x > 0 
      return x;
   else
      return -x
}
Run Code Online (Sandbox Code Playgroud)

我正在努力为它找到一个解决方案而不使用模数运算符.

小智 19

在我看来似乎

floor(n) = n - (n % 1)
Run Code Online (Sandbox Code Playgroud)

应该做的伎俩.


zku*_*nov 6

使用IEEE 754 二进制浮点表示形式,一种可能的解决方案是:

float myFloor(float x)
{
  if (x == 0.0)
    return 0;

  union
  {
    float input;   // assumes sizeof(float) == sizeof(int)
    int   output;
  } data;

  data.input = x;

  // get the exponent 23~30 bit    
  int exp = data.output & (255 << 23);
  exp = exp >> 23;

  // get the mantissa 0~22 bit
  int man = data.output & ((1 << 23) - 1);

  int pow = exp - 127;
  int mulFactor = 1;

  int i = abs(pow);
  while (i--)
    mulFactor *= 2;

  unsigned long long denominator = 1 << 23;
  unsigned long long numerator = man + denominator;

  // most significant bit represents the sign of the number
  bool negative = (data.output >> 31) != 0;

  if (pow < 0)
    denominator *= mulFactor;
  else
    numerator *= mulFactor;

  float res = 0.0;
  while (numerator >= denominator) {
    res++;
    numerator -= denominator;
  }

  if (negative) {
    res = -res;
    if (numerator != 0)
      res -= 1;
  }

  return res;
}


int main(int /*argc*/, char **/*argv*/)
{
  cout << myFloor(-1234.01234) << " " << floor(-1234.01234) << endl;

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • @FaridNouriNeshat 这个答案实际上可能与其他答案相同,但显示了如何使用位级指令来实现“int(value)”。(如果我最初提出这个问题,这就是我正在寻找的答案,并且我会很失望地得到其他看起来显而易见的答案。) (3认同)