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
CCode Cell
1#include <stdio.h>
2#include <math.h>
3 
4int main()
5{
6 // 1. Square Root
7 printf("sqrt(144) = %.2f\n", sqrt(144.0));
8 
9 // 2. Power
10 printf("pow(2, 10) = %.0f\n", pow(2.0, 10.0));
11 
12 // 3. Absolute Value of Floating-Point Number
13 printf("fabs(-7.5) = %.2f\n", fabs(-7.5));
14 
15 // 4. Floating-Point Remainder
16 printf("fmod(10.5, 3) = %.2f\n", fmod(10.5, 3.0));
17 
18 // 5. Ceiling: Round Up
19 printf("ceil(4.3) = %.2f\n", ceil(4.3));
20 
21 // 6. Floor: Round Down
22 printf("floor(4.8) = %.2f\n", floor(4.8));
23 
24 // 7. Round to Nearest Integer
25 printf("round(4.6) = %.2f\n", round(4.6));
26 
27 // 8. Truncate Decimal Part
28 printf("trunc(4.9) = %.2f\n", trunc(4.9));
29 
30 // 9. Maximum Value
31 printf("fmax(10, 20) = %.2f\n", fmax(10.0, 20.0));
32 
33 // 10. Minimum Value
34 printf("fmin(10, 20) = %.2f\n", fmin(10.0, 20.0));
35 
36 // 11. Absolute Value of an Integer
37 printf("abs(-25) = %d\n", abs(-25));
38 
39 return 0;
40}
Output
sqrt(144) = 12.00
pow(2, 10) = 1024
fabs(-7.5) = 7.50
fmod(10.5, 3) = 1.50
ceil(4.3) = 5.00
floor(4.8) = 4.00
round(4.6) = 5.00
trunc(4.9) = 4.00
fmax(10, 20) = 20.00
fmin(10, 20) = 10.00
abs(-25) = 25

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