In this source code example, we will see how to use the log10() function in C programming with an example.
log10() Function Overview
The log10() function in C computes the base-10 logarithm (common logarithm) of a given number. This function is particularly useful when working with values that are powers of 10, such as in many engineering, physics, and financial applications. The function resides within the math.h library.
Key Points:
- To employ the log10() function, you must include the math.h header.
- The function calculates the logarithm with base 10.
- The provided argument must be positive. If a non-positive value is provided, the function will return a domain error.
- Always link the math library using the -lm flag when compiling.
Source Code Example
#include <stdio.h>
#include <math.h> // Necessary for log10()
int main() {
double value, result;
// Ask for user input
printf("Enter a positive value to compute its base-10 logarithm: ");
scanf("%lf", &value);
if(value <= 0) {
printf("Error: Please input a positive number.\n");
return 1;
}
// Compute the base-10 logarithm of the given value
result = log10(value);
// Display the result
printf("Base-10 logarithm of %.2lf is: %.2lf\n", value, result);
return 0;
}
Output
Enter a positive value to compute its base-10 logarithm: 100 Base-10 logarithm of 100.00 is: 2.00
Explanation
1. We begin by including the essential header files: stdio.h for basic input/output functions and math.h for the log10() function.
2. In the main() function, we prompt the user for an input value.
3. A check ensures that the user-provided value is positive. If not, an error message is displayed, and the program exits.
4. If a valid input is given, the log10() function computes its base-10 logarithm.
5. The calculated result is then showcased to the user via the console.
Comments
Post a Comment