English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Usage and examples of log() function

C++ Library Function <cmath>

C ++the natural logarithm of the parameter (base e logarithm) in

This function returns<cmath>defined in the header file.

logex = log(x)

log() prototype [from C ++ 11Standard start]

double log(double x);
float log(float x);
long double log(long double x);
double log(T x);  //as integer

log() parameters

The log() function uses[0, ∞]A single required parameter within the range.

If the value is less than zero, log() returns NaN (Not a Number).

log() return value

The log() function returns the natural logarithm of a number.

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

Example1How does log() work?

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
	double x = 13.056, result;
	result = log(x);
	cout << "log(x) = " << result << endl;
	x = -3.591;
	result = log(x);
	cout << "log(x) = " << result << endl;
	return 0;
}

When the program runs, the output is:

log(x) = 2.56925
log(x) = nan

Example2: log() with integer type

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
	int x = 2;
	double result;
	result = log(x);
	cout << "log(x) = " << result << endl;
	return 0;
}

When the program runs, the output is:

log(x) = 0.693147

C++ Library Function <cmath>