log() function in C++

In this tutorial, we will learn about log function in C++.

log() function in C++

log() is the natural logarithmic function. It is the inverse of natural exponential function (e). When we use log() function, it returns the value with respect to base e. Another function similar to this is log10(). This gives us value with respect to base 10.

The syntax for the functions are :

log(x);
log10(x);

We use the following header file with the functions :

#include <math.h>

The parameter x can be of int, float, double or long double type. We get return value as float, double or long double respectively. The return types of the parameters are as follows :

Parameter (x) Return VALUE
x > 1 Positive
x = 1 0
0 > x > 1 Negative
x = 0 -∞ (- infinity)
x < 0 NaN (Not a Number)

Here is an example displaying the use of the log() and log10() functions in C++.

A C++ program using log() and log10() functions :

#include<iostream>
#include<math.h>
using namespace std;
int main()
{
  double k, r, r10;
  cout << "Enter value of k : ";
  cin >> k;
  r = log(k);
  r10 = log10(k);
  cout << "log(k) = " << r << endl;
  cout << "log10(k) = " << r10 << endl;
  return 0;
}

Output 1 :

Enter value of k : 6.2
log(k) = 1.82455
log10(k) = 0.792392

Output 2 :

Enter value of k : 0.54
log(k) = -0.616186
log10(k) = -0.267606

Hope this was helpful. Enjoy Coding!

Also, learn :

Mathematical Constants in C++

Mathematical functions in CPP

Leave a Reply

Your email address will not be published. Required fields are marked *