log() Function with Example in C++

C++ log() function: Here, we are going to learn about the log() function with example of cmath header in C++ programming language.
Submitted by IncludeHelp, on May 20, 2020

C++ log() function

log() function is a library function of cmath header, it is used to get the natural logarithm (the base-e logarithm) of the given value. It accepts a value (float, double, or long double) and returns the natural logarithm.

Syntax of log() function:

C++11:

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

Parameter(s):

  • x – represents the value whose natural logarithm to be found.

Return value:

It returns the natural logarithm of the given value x.

Note:

  • If the given value is negative, it causes a domain error.
  • If the given value is zero, it may cause a pole error.

Example:

    Input:
    float x = 1.0f
    
    Function call:
    log(x);
    
    Output:
    0

C++ code to demonstrate the example of log() function

// C++ code to demonstrate the example of
// log() function

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

int main()
{
    float x = 0.0f;

    x = 10.0f;
    cout << "log(" << x << "): " << log(x) << endl;

    x = 1.0f;
    cout << "log(" << x << "): " << log(x) << endl;

    x = 20.0f;
    cout << "log(" << x << "): " << log(x) << endl;

    x = -10.4f;
    cout << "log(" << x << "): " << log(x) << endl;

    x = 0.0f;
    cout << "log(" << x << "): " << log(x) << endl;

    x = 100.6f;
    cout << "log(" << x << "): " << log(x) << endl;

    return 0;
}

Output

log(10): 2.30259
log(1): 0
log(20): 2.99573
log(-10.4): nan
log(0): -inf
log(100.6): 4.61115

Reference: C++ log() function



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.