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)
我正在努力为它找到一个解决方案而不使用模数运算符.
使用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)