Nearby lessons
82 of 124C - Math Functions
The <math.h> library gives C its mathematics: sqrt, pow, fabs, ceil, floor, round, trigonometry, logarithms and more. Learn the full set, plus the -lm linker flag that trips up every beginner.
The Essential Functions
| Function | Returns | Example | Result |
|---|---|---|---|
sqrt(x) | Square root | sqrt(25) | 5.0 |
pow(x, y) | x to the power y | pow(2, 10) | 1024.0 |
fabs(x) | Absolute value | fabs(-7.5) | 7.5 |
ceil(x) | Round up | ceil(4.1) | 5.0 |
floor(x) | Round down | floor(4.9) | 4.0 |
round(x) | Nearest integer | round(4.5) | 5.0 |
fmod(x, y) | Floating remainder | fmod(10.5, 3) | 1.5 |
Compiling — The -lm Flag
undefined reference to 'sqrt'. Including <math.h> only tells the compiler what sqrt looks like — you must also tell the linker where the code lives. On Linux and macOS with gcc, add -lm:The Three Rounding Functions
ceil always goes up, floor always goes down, round goes to the nearest. Watch how they differ on negatives:
fabs vs abs
Two different functions in two different headers. Using abs on a double truncates it first:
Trigonometry Works in Radians
sin, cos and tan expect radians. Convert from degrees with degrees × π / 180:
Logarithms and Exponentials
log is the natural logarithm (base e); log10 is base 10. exp(x) computes e to the power x:
A Practical Example — Distance
sqrt and pow together give the classic distance formula:
Rounding to Decimal Places
printf rounds for display only. To round the stored value, scale up, round, and scale back:
Guard Against Invalid Input
sqrt of a negative and log of zero produce nan and -inf. Check before you call:
Common Mistakes
- Forgetting
-lm—undefined reference to 'sqrt'at link time. - Passing degrees to
sin— the functions take radians. - Using
abson a double — truncates before taking the absolute value. Usefabs. - Expecting
logto be base 10 — it is base e. Uselog10. pow(2, 3)for integers — returns adoubleand is slower than2 * 2 * 2.- Comparing floats with
==—sqrt(2) * sqrt(2) == 2is false. Compare within a tolerance.
sqrt(2.0) * sqrt(2.0) comes out as 2.0000000000000004. Write fabs(a - b) < 1e-9 instead of a == b.- Include <math.h> to use any of these functions.
- On Linux and macOS, compile with gcc file.c -lm.
- Most math.h functions take and return double.
- Use fabs for floating-point absolute value, abs for int.
- Trigonometric functions work in radians, not degrees.