Lesson 52: Standard Library Functions (Math Library)
C's strength lies in its extensive set of standard library functions. To use mathematical functions, you must include <math.h>.
Note: When compiling a program that uses <math.h>, you usually need to link the math library using the -lm flag with GCC (e.g., gcc program.c -o program -lm).
Common Mathematical Functions
| Function | Description | Example |
|---|---|---|
sqrt(x) | Returns the square root of x | double result = sqrt(25.0); (5.0) |
pow(x, y) | Returns x raised to the power of y | double result = pow(2.0, 3.0); (8.0) |
sin(x), cos(x), tan(x) | Trigonometric functions (x in radians) | double s = sin(1.57); |
fabs(x) | Returns the absolute value of a floating-point number | double abs = fabs(-10.5); (10.5) |
ceil(x) | Returns the smallest integer greater than or equal to x | double c = ceil(4.2); (5.0) |
floor(x) | Returns the largest integer less than or equal to x | double f = floor(4.9); (4.0) |
Example Usage
c #include <stdio.h> #include <math.h>
int main() { double a = 9.0; double b = 2.0;
// Calculate hypotenuse using Pythagorean theorem
double c_squared = pow(a, 2.0) + pow(b, 2.0);
double hypotenuse = sqrt(c_squared);
printf("Hypotenuse: %.2f\n", hypotenuse);
return 0;
}
Type Requirement: Most functions in <math.h> expect and return double types. If you work with float or long double, specific variants exist (e.g., sqrtf, sqrtl).