floor()/int() 函数实现

问题描述 投票:0回答:7

有谁知道方法/功能

Int()
floor()
是如何实现的? 我正在寻找相应的实现,因为以下是
abs()
功能。

Int Abs (float x){
  if x > 0 
      return x;
   else
      return -x
}

我正在努力寻找不使用模数运算符的解决方案。

function implementation
7个回答
26
投票

在我看来

floor(n) = n - (n % 1)

应该做的伎俩。


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;
}

4
投票
private static int fastFloor(double x) {
    int xi = (int)x;
    return x < xi ? xi - 1 : xi;
}

这是一种类似于 Michal Crzardybons 答案的方法,但它避免了条件分支并且仍然正确处理负数。


2
投票

如果“int”类型的结果就足够了,那么这里有一个简单的替代方案:

int ifloor( float x )
{
    if (x >= 0)
    {
        return (int)x;
    }
    else
    {
        int y = (int)x;
        return ((float)y == x) ? y : y - 1;
    }
}

0
投票
int(x)   = x - x%1
floor(x) = int(x)-(x<0 && x%1!=0)
ceil(x)  = int(x)+(x>0 && x%1!=0)
round(x) = floor(x)+(x>0&&x%1>=0.5)+(x<0&&(1+x%1)%1>=0.5)

注意:

round(x)
没有实现为
floor(x+0.5)
因为这将在
x=0.5-2^-54

失败

注意: 假设逻辑运算转换为整数值,1 表示真,0 表示假


实现已完成,因此它们匹配

int(x)
floor(x)
ceil(x)
round(x)

中定义的域

0
投票

最佳答案不适用于负数所以我修改了它:

floor(n) = n - (n % 1 >= 0 ? n%1: (1 + n % 1))
ceil(n) = -floor(-n)

0
投票
#include<iostream>

int myfloor(int x) {
    if (x > 0)
        return x;
    else
        return x - 1;
}
int main() {
    double x = -5.9;
    std::cout<<myfloor(x);
}
© www.soinside.com 2019 - 2024. All rights reserved.