What is the log() function in C++?

Overview

In C++, the log() function is used to return the natural logarithm of the argument x that is passed to it.

Mathematically, the natural logarithm of a number is given by:

Log(x) = Log Log10Log_{10}x

Syntax

double log (double x);
float log (float x);
long double log (long double x);

Parameter value

The log() function takes a single parameter value x, which represents the number whose natural logarithm is to be computed. This parameter value must be between zero (0) and infinity().

Any value passed to the function that is less than zero (0) will return NaN.

Return value

The log() function returns the natural logarithm of the argument x that is passed to it.

Code example

#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
// creating variables
int x = 100;
double result;
// implementing the log() function
result = log (x);
cout << "log(100) = " << result << endl;
return 0;
}

Code explanation

  • Lines 8–9: We create the variables x and result.
  • Line 12: We implement the log() function on the value of the x variable and assign the output to the result variable.
  • Line 13: We print the result variable.

Free Resources