C++ 参考手册

位置:首页 > C++ 参考手册 >数值库 >常用数学函数 > std::exp2, std::exp2f, std::exp2l

定义于头文件 <cmath>
float       exp2 ( float n );
float       exp2f( float n );
(1) (C++11 起)
double      exp2 ( double n );
(2) (C++11 起)
long double exp2 ( long double n );
long double exp2l( long double n );
(3) (C++11 起)
double      exp2 ( IntegralType n );
(4) (C++11 起)
1-3) 计算 2 的给定 n 次幂。
4) 接收任何整数类型参数的重载集或函数模板。等价于 (2) (将参数转型为 double )。

参数

n - 浮点或整数类型

返回值

若不出现错误,则返回 n 的底 2 指数( 2n
)。

若出现上溢所致的值域错误,则返回 +HUGE_VAL+HUGE_VALF+HUGE_VALL

若出现下溢所致的值域错误,则返回(舍入后的)正确结果。

错误处理

报告 math_errhandling 中指定的错误。

若实现支持 IEEE 浮点算术( IEC 60559 ),则

  • 若参数为 ±0 ,则返回 1
  • 若参数为 -∞ ,则返回 +0
  • 若参数为 +∞ ,则返回 +∞
  • 若参数为 NaN ,则返回 NaN

示例

#include <iostream>
#include <cmath>
#include <cerrno>
#include <cstring>
#include <cfenv>
#pragma STDC FENV_ACCESS ON
int main()
{
    std::cout << "exp2(4) = " << std::exp2(4) << '\n'
              << "exp2(0.5) = " << std::exp2(0.5) << '\n'
              << "exp2(-4) = " << std::exp2(-4) << '\n';
    // 特殊值
    std::cout << "exp2(-0) = " << std::exp2(-0.0) << '\n'
              << "exp2(-Inf) = " << std::exp2(-INFINITY) << '\n';
    // 错误处理
    errno = 0;
    std::feclearexcept(FE_ALL_EXCEPT);
    std::cout << "exp2(1024) = " << std::exp2(1024) << '\n';
    if (errno == ERANGE)
        std::cout << "    errno == ERANGE: " << std::strerror(errno) << '\n';
    if (std::fetestexcept(FE_OVERFLOW))
        std::cout << "    FE_OVERFLOW raised\n";
}

可能的输出:

exp2(4) = 16
exp2(0.5) = 1.41421
exp2(-4) = 0.0625
exp2(-0) = 1
exp2(-Inf) = 0
exp2(1024) = inf
    errno == ERANGE: Numerical result out of range
    FE_OVERFLOW raised

参阅

(C++11)(C++11)
返回 e 的给定次幂( ex
(函数)
(C++11)(C++11)(C++11)
返回 e 的给定次幂减一( ex-1
(函数)
(C++11)(C++11)(C++11)
给定数值的以 2 为底的对数( log2(x)
(函数)