In this C++ tutorial, you will learn how to find base-2 logarithm of given number using log2() function of cmath, with syntax and examples.
C++ log2()
C++ log2() returns base-2 logarithm of given number (argument).
Syntax
The syntax of C++ log2() is
log2(x)
where
Parameter | Description |
---|---|
x | A double, float, long double, or any integral type value. |
Returns
The return value depends on the type of value passed for parameter x.
The return value of log2(x) is
- double if x is double or integral type.
- float if x is float.
- long double if x is long double.
The synopsis of log2() function is
double log2 (double x);
float log2 (float x);
long double log2 (long double x);
double log2 (T x); // for integral type argument values
log2() is a function of cmath library. Include cmath library at the start of program, if using log2() function.
Example
In this example, we read a value from user into variable x, and find its base-2 logarithm value using log2() function.
C++ Program
#include <iostream>
#include<cmath>
using namespace std;
int main() {
double x;
cout << "Enter a number : ";
cin >> x;
double result = log2(x);
cout << "log2(" << x << ") : " << result << endl;
}
Output
Enter a number : 16
log2(16) : 4
Program ended with exit code: 0
Enter a number : 1
log2(1) : 0
Program ended with exit code: 0
Enter a number : -5
log2(-5) : nan
Program ended with exit code: 0
Conclusion
In this C++ Tutorial, we learned the syntax of C++ log2(), and how to use this function to find base-2 logarithm of given number, with the help of examples.