In this C++ tutorial, you will learn how to find the natural logarithm of given number using log() function of cmath, with syntax and examples.

C++ log()

C++ log() returns natural logarithm of given number. It computes the logarithm of given value to base-e.

Syntax

The syntax of C++ log() is

log(x)

where

ParameterDescription
xA double, float, long double, or integral type value. The value of x must be in the range [0, inf].

Returns

The return value depends on the type of value passed for parameter x. The return value of log(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 log() function is

double log (double x);
float log (float x);
long double log (long double x);
double log (T x);// for integral type argument values

log() is a function of cmath library. Include cmath library at the start of program, if using log() function.

Example

In this example, we read a value from user into variable x, and find its logarithm value using log().

C++ Program

#include <iostream>
#include<cmath>
using namespace std;

int main() {
    double x;
    cout << "Enter a number : ";
    cin >> x;
    
    double result = log(x);
    cout << "log(" << x << ") : " << result << endl;
}

Output

Enter a number : 1
log(1) : 0
Program ended with exit code: 0
Enter a number : 5
log(5) : 1.60944
Program ended with exit code: 0
Enter a number : -2
log(-2) : nan
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned the syntax of C++ log(), and how to use this function to find the natural logarithm of given number, with the help of examples.