Nearby lessons
51 of 72C - 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 |
Example01
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.
Trainer's Note: never test floating-point results for exact equality.
sqrt(2.0) * sqrt(2.0) comes out as 2.0000000000000004. Write fabs(a - b) < 1e-9 instead of a == b.📝 Key Takeaways
- 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.
🧠 Test Your Knowledge
4 QuestionsProgress: 0 / 4