获取浮点数的尾数和指数

获取浮点数的尾数和指数#

参考:frexp

float frexp(
   float x,
   int * expptr
);  // C++ only
long double frexp(
   long double x,
   int * expptr
);  // C++ only

参数:

  • x:浮点值。

  • expptr:指向存储的整数指数的指针。

frexp() 返回尾数。 如果 x0,则该函数将返回 0 表示尾数和指数。如果 expptrNULL,则调用无效的参数处理程序,如参数验证中所述。 如果允许执行继续,则该函数将 errno 设置为 EINVAL 并返回 0

备注

frexp 函数将浮点值(x)分解为尾数(mantissa m)和指数(exponent,n),使绝对值 m 大于或等于 0.5 且小于 1.0,并且 x=m2n。整数指数 n 存储在由 expptr 指向的位置。

#include <iostream>
double x, y;
int n;
x = 16.4;
y = frexp(x, &n);
std::cout << "std::frexp(x, &n) => " 
         << x << " = " << y << " * "
         << "(1 << " << n << ")";
std::frexp(x, &n) => 16.4 = 0.5125 * (1 << 5)

将双精度有效数字转换为整数有效数字,即将小数点放在第 31 位和第 30 位之间。这是通过将双精度值乘以 231,然后将其转换为 int 来实现的。