當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ logb()用法及代碼示例


logb()是C++ STL中的內置函數,它使用FLT_RADIX作為對數的底數,返回| x |的對數。通常,FLT_RADIX的值為2,因此logb()等效於log2()(僅適用於正值)。

用法

logb(val)

參數:該函數接受單個強製參數val,該參數指定要計算其logb()的val。數據類型可以是double,float,long double或int。


返回類型:該函數返回| x |的對數。

以下示例程序旨在說明上述函數:

程序1

// C++ program to illustrate 
// to implement logb() function 
// when data-type is integer 
#include <cmath> 
#include <iostream> 
using namespace std; 
int main() 
{ 
    double result; 
    int x = -10; 
  
    result = logb(x); 
    cout << "logb(" << x << ") = "
         << "log(|" << x << "|) = " << result << endl; 
  
    x = 10; 
  
    result = logb(x); 
    cout << "logb(" << x << ") = "
         << "log(|" << x << "|) = " << result << endl; 
  
    return 0; 
}
輸出:
logb(-10) = log(|-10|) = 3
logb(10) = log(|10|) = 3

程序2

// C++ program to illustrate 
// to implement logb() function 
// when data-type is double 
#include <cmath> 
#include <iostream> 
  
using namespace std; 
  
int main() 
{ 
    double x = 70.56, result; 
  
    result = logb(x); 
    cout << "logb(" << x << ") = "
         << "log(|" << x << "|) = " << result << endl; 
  
    x = 17.6; 
  
    result = logb(x); 
    cout << "logb(" << x << ") = "
         << "log(|" << x << "|) = " << result << endl; 
  
    return 0; 
}
輸出:
logb(70.56) = log(|70.56|) = 6
logb(17.6) = log(|17.6|) = 4

程序3

// C++ program to illustrate 
// to implement logb() function 
// when input is 0 
#include <cmath> 
#include <iostream> 
  
using namespace std; 
  
int main() 
{ 
    double result; 
    int x = 0; 
  
    result = logb(x); 
    cout << "logb(" << x << ") = "
         << "log(|" << x << "|) = " << result << endl; 
  
    return 0; 
}
輸出:
logb(0) = log(|0|) = -inf


相關用法


注:本文由純淨天空篩選整理自IshwarGupta大神的英文原創作品 logb() function in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。