Open In App

log10() Function in C++

Last Updated : 22 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The std::log10() in C++ is a built-in function that is used to calculate the base-10 logarithm of a given number. It is defined inside <cmath> header file. In this article, we will learn about log10() in C++ and its behavior for different values.

Example:

C++
// C++ Program to illustrate the use of log10()
#include <iostream>
#include <cmath>
using namespace std;

int main() {
  	
    cout << log10(100.00) << endl;
  	cout << log10(1);
  
    return 0;
}

Output
2
0

log10() Syntax

std::log10(n);

Parameters

  • n: Value whose base 10 logarithm is to be calculated. Can be of any numeric type such as int, long, float, double, etc.

Return Value

The log10() function returns different values depending on the parameter:

  • Returns base 10 logarithm of given number, if number is greater than 1.
  • Return negative integer, if number is in between 0 and 1 (not inclusive).
  • Returns -inf (infinity) , if the number is 0.
  • Returns inf (infinity) , if the number is very large.
  • Returns NaN (Not a Number), if the number is negative.

More Examples of log10()

The following examples demonstrate the behaviors of std::log10() function in different scenarios.

Example 1: Calculating log10() for Different Number Types

C++
// C++ Program to compute log10() for different
// number types
#include <bits/stdc++.h>
using namespace std;

int main() {

    // Calculating log10() for different
  	// types of numeric values
    cout << log10(100) << endl;
    cout << log10(1000.5f) << endl;
    cout << log10(10000.123);

    return 0;
}

Output
2
3.00022
4.00001

Example 2: Using log10() for Negative Numbers and Zero

C++
// C++ Program to check the output of log10()
// with negative numbers
#include <iostream>
#include <cmath>
using namespace std;

int main() {
    
    // log10 of a negative number
    cout << log10(-100.0) << endl;
  
  	// log10 of a negative number
  	cout << log10(0);
    return 0;
}

Output
nan
-inf

Next Article
Practice Tags :

Similar Reads