math.h
The <math.h> header declares the standard C library's floating-point mathematical functions — square roots, powers, trigonometry, logarithms, and rounding. These functions operate on double (with float- and long double-suffixed variants like sqrtf/sqrtl available since C99).
Commonly Used Functions
Function | Signature | Purpose |
|---|---|---|
sqrt | double sqrt(double x) | Square root of x |
pow | double pow(double base, double exp) | base raised to the power exp |
fabs | double fabs(double x) | Absolute value of a floating-point number |
ceil | double ceil(double x) | Rounds up to the nearest integer value |
floor | double floor(double x) | Rounds down to the nearest integer value |
round | double round(double x) | Rounds to the nearest integer (halves away from zero) |
sin, cos, tan | double sin(double x) | Trigonometric functions (radians, not degrees) |
log | double log(double x) | Natural logarithm (base e) |
log10 | double log10(double x) | Base-10 logarithm |
exp | double exp(double x) | e raised to the power x |
A Quick Tour
#include <stdio.h>
#include <math.h>
int main(void) {
double x = 2.0;
printf("sqrt(2.0) = %f\n", sqrt(x));
printf("pow(2, 10) = %f\n", pow(x, 10));
printf("fabs(-3.5) = %f\n", fabs(-3.5));
printf("ceil(4.2) = %f\n", ceil(4.2));
printf("floor(4.8) = %f\n", floor(4.8));
printf("round(4.5) = %f\n", round(4.5));
printf("sin(0.0) = %f\n", sin(0.0));
printf("log10(1000) = %f\n", log10(1000.0));
printf("exp(1.0) = %f\n", exp(1.0));
return 0;
}Compiling: Don't Forget -lm
On Linux (and many other Unix-like systems using glibc), the math functions live in a separate library file, libm, that is not linked by default. If you compile a program that calls sqrt, pow, or other math.h functions and forget the linker flag, you'll get an "undefined reference" error at link time even though the code compiles cleanly.
# Correct: link against the math library gcc program.c -o program -lm # Missing -lm often produces an error like: # undefined reference to `sqrt'
abs() vs fabs(): A Classic Mix-Up
C has two "absolute value" functions that are easy to confuse: abs() (declared in <stdlib.h>) operates on int, while fabs() (declared in <math.h>) operates on double. Passing a floating-point number to abs() truncates it to an integer first, silently discarding the fractional part.
#include <stdio.h>
#include <stdlib.h> /* for abs() — integers */
#include <math.h> /* for fabs() — doubles */
int main(void) {
double d = -3.75;
printf("abs(d) = %d\n", abs((int)d)); /* WRONG intent: truncates -3.75 to -3, then abs -> 3 */
printf("fabs(d) = %f\n", fabs(d)); /* CORRECT: 3.750000 */
return 0;
}