Nearby lessons

51 of 72

C - 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

FunctionReturnsExampleResult
sqrt(x)Square rootsqrt(25)5.0
pow(x, y)x to the power ypow(2, 10)1024.0
fabs(x)Absolute valuefabs(-7.5)7.5
ceil(x)Round upceil(4.1)5.0
floor(x)Round downfloor(4.9)4.0
round(x)Nearest integerround(4.5)5.0
fmod(x, y)Floating remainderfmod(10.5, 3)1.5
Example01
Loading editor…

Common Mistakes

  • Forgetting -lm — undefined reference to 'sqrt' at link time.
  • Passing degrees to sin — the functions take radians.
  • Using abs on a double — truncates before taking the absolute value. Use fabs.
  • Expecting log to be base 10 — it is base e. Use log10.
  • pow(2, 3) for integers — returns a double and is slower than 2 * 2 * 2.
  • Comparing floats with == — sqrt(2) * sqrt(2) == 2 is 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 Questions
Progress: 0 / 4

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.