Mathematical Functions
C provides a variety of mathematical functions through the <math.h> header file. These functions are used for arithmetic, trigonometric, logarithmic, exponential, and other mathematical computations.
Here are some of the most commonly used mathematical functions in C:
Function | Description | Example | Output |
---|---|---|---|
sqrt(x) | Square root of x. | sqrt(16) | 4.0 |
pow(x, y) | x raised to the power of y. | pow(2, 3) | 8.0 |
abs(x) | Absolute value of an integer x. | abs(-5) | 5 |
fabs(x) | Absolute value of a floating-point number x. | fabs(-3.14) | 3.14 |
ceil(x) | Smallest integer >= x (round up). | ceil(3.7) | 4.0 |
floor(x) | Largest integer <= x (round down). | floor(3.7) | 3.0 |
round(x) | Round x to the nearest integer. | round(3.5) | 4.0 |
exp(x) | Exponential (e^x). | exp(1) | 2.71828 |
log(x) | Natural logarithm (base e) of x. | log(2.71828) | 1.0 |
log10(x) | Base-10 logarithm of x. | log10(100) | 2.0 |
sin(x) | Sine of x (in radians). | sin(3.14159 / 2) | 1.0 |
cos(x) | Cosine of x (in radians). | cos(0) | 1.0 |
tan(x) | Tangent of x (in radians). | tan(3.14159 / 4) | 1.0 |
asin(x) | Inverse sine (arcsine) of x. | asin(1) | 1.5708 |
acos(x) | Inverse cosine (arccos) of x. | acos(1) | 0.0 |
atan(x) | Inverse tangent (arctan) of x. | atan(1) | 0.785398 |
atan2(y, x) | Arctangent of y/x, considering quadrant. | atan2(1, 1) | 0.785398 |
hypot(x, y) | Hypotenuse of a right-angled triangle with sides x and y. | hypot(3, 4) | 5.0 |
cbrt(x) | Cube root of x. | cbrt(27) | 3.0 |
fmod(x, y) | Remainder of x/y. | fmod(5.3, 2.1) | 1.1 |
Example:
#include <stdio.h>
#include <math.h>
int main() {
double num = 9.0;
printf("Square root of %.2f: %.2f\n", num, sqrt(num));
printf("2 raised to the power 3: %.2f\n", pow(2, 3));
printf("Absolute value of -7: %d\n", abs(-7));
printf("Ceiling of 2.3: %.2f\n", ceil(2.3));
printf("Floor of 2.7: %.2f\n", floor(2.7));;
printf("Sin of PI/2 radians: %.2f\n", sin(M_PI / 2)); // M_PI is the value of π
return 0;
}
Output
Square root of 9.00: 3.00
2 raised to the power 3: 8.00
Absolute value of -7: 7
Ceiling of 2.3: 3.00
Floor of 2.7: 2.00
Sin of PI/2 radians: 1.00