C - Math Functions
The <math.h> header file provides a set of mathematical functions that you can use in your programs. These functions allow you to perform various mathematical operations, such as trigonometric calculations, logarithmic calculations, exponentiation, rounding, and more. Here are some commonly used math functions in C:
Trigonometric Functions:
- sin(x): Returns the sine of the angle x (in radians).
- cos(x): Returns the cosine of the angle x (in radians).
- tan(x): Returns the tangent of the angle x (in radians).
- asin(x): Returns the arc sine (inverse sine) of x in radians.
- acos(x): Returns the arc cosine (inverse cosine) of x in radians.
- atan(x): Returns the arc tangent (inverse tangent) of x in radians.
- atan2(y, x): Returns the arc tangent of y/x in radians, using the signs of both arguments to determine the quadrant of the result.
Exponential and Logarithmic Functions:
- exp(x): Returns the exponential value of x (e^x).
- log(x): Returns the natural logarithm (base e) of x.
- log10(x): Returns the common logarithm (base 10) of x.
- pow(x, y): Returns x raised to the power of y.
- sqrt(x): Returns the square root of x.
Rounding and Absolute Value Functions:
- ceil(x): Returns the smallest integer greater than or equal to x.
- floor(x): Returns the largest integer less than or equal to x.
- round(x): Returns the nearest integer value to x.
- fabs(x): Returns the absolute value of x.
Other Useful Functions:
- fmod(x, y): Returns the remainder of x divided by y.
- rand(): Generates a pseudo-random number.
- srand(seed): Sets the seed value for the rand() function.
To use these math functions, make sure to include the <math.h> header file at the beginning of your program.
#include <stdio.h>
#include <math.h>
int main() {
double x = 2.5;
double result = sin(x);
printf("sin(%.2f) = %.2f\n", x, result);
int number = -10;
int absValue = abs(number);
printf("Absolute value of %d = %d\n", number, absValue);
return 0;
}
In this example, the sin() function from <math.h> is used to calculate the sine of x. The abs() function is used to find the absolute value of number. The results are printed using printf().