📜  C++ STL中的exp2()函数

📅  最后修改于: 2021-05-25 20:05:54             🧑  作者: Mango

exp2()是C++ STL中的内置函数,用于计算给定数字的以2为底的指数函数。也可以写为2 num

语法

exp2(data_type num)

参数:该函数接受单个强制参数num ,该参数指定指数的值。它可以是正数,负数或0。参数的类型可以是double,float或long double。

返回值:它返回double,float或long double值,该值等于2 num

程序1

// C++ program to illustrate the
// exp2() function for negative double numbers
#include 
#include 
  
using namespace std;
  
int main()
{
    double n = -3.14;
  
    double ans = exp2(n);
    cout << "exp2(-3.14) = " << ans << endl;
  
    return 0;
}
输出:
exp2(-3.14) = 0.11344

程序2

// C++ program to illustrate the
// exp2() function for positive numbers
#include 
#include 
  
using namespace std;
  
int main()
{
    int n = 6;
  
    int ans = exp2(n);
    cout << "exp2(6) = " << ans << endl;
  
    return 0;
}
输出:
exp2(6) = 64

程序3

// C++ program to illustrate the
// exp2() function for 0
#include 
#include 
  
using namespace std;
  
int main()
{
    int n = 0;
  
    int ans = exp2(n);
    cout << "exp2(0) = " << ans << endl;
  
    return 0;
}
输出:
exp2(0) = 1

错误和例外:如果结果的大小太大而无法用返回类型的值表示,则该函数将返回带有正确符号的HUGE_VAL(或HUGE_VALF或HUGE_VALL),并且会发生溢出范围错误

下面的程序说明了该错误。

// C++ program to illustrate the
// exp2() function for range overflow
#include 
#include 
  
using namespace std;
  
int main()
{
    // overflow will occur as 2^100 will not
    // fit to int data-type
    int n = 100;
  
    int ans = exp2(n);
    cout << "exp2(100) = " << ans << endl;
  
    return 0;
}
输出:
exp2(100) = -2147483648
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”