C Math Functions

The C standard library gives you a rich set of math functions in the <math.h> header. These functions handle square roots, powers, rounding, trigonometry, and more, so you do not have to write the math yourself. Just remember to include <math.h> at the top of your program.

Including the Math Library

Before you can use any math function, you must include the math header. Most math functions work with the double type and return a double, so keep that in mind when you print or store the results.

Square root with sqrt()

#include <stdio.h>
#include <math.h>

int main() {
  double x = 144.0;
  printf("Square root of %.0f is %.1f\n", x, sqrt(x));
  return 0;
}

The output of this program is:

Output

Square root of 144 is 12.0
Note: On some compilers, such as gcc on Linux, you must link the math library by adding -lm when you compile, for example: gcc program.c -o program -lm.

Common Math Functions

Here are some of the most widely used functions from <math.h>. All of them expect double values and return a double result.

FunctionDescriptionExampleResult
sqrt(x)Square root of xsqrt(16.0)4.0
pow(x, y)x raised to the power ypow(2.0, 3.0)8.0
ceil(x)Rounds x up to nearest integerceil(4.2)5.0
floor(x)Rounds x down to nearest integerfloor(4.8)4.0
fabs(x)Absolute value of xfabs(-9.5)9.5
round(x)Rounds x to nearest integerround(4.5)5.0

Powers, Rounding, and Absolute Values

The pow() function is handy for exponents, while ceil(), floor(), and round() let you control how decimals become whole numbers. The example below shows several of them working together.

Using pow, ceil, floor, and fabs

#include <stdio.h>
#include <math.h>

int main() {
  printf("2 to the power 10 = %.0f\n", pow(2.0, 10.0));
  printf("ceil(7.1)  = %.0f\n", ceil(7.1));
  printf("floor(7.9) = %.0f\n", floor(7.9));
  printf("fabs(-3.7) = %.1f\n", fabs(-3.7));
  return 0;
}

Running the program produces:

Output

2 to the power 10 = 1024
ceil(7.1)  = 8
floor(7.9) = 7
fabs(-3.7) = 3.7
  • Use %f in printf to display double results, and control the decimals with something like %.2f.
  • fabs() is for floating-point numbers; for integers use abs() from <stdlib.h> instead.
  • pow() always returns a double, even when the answer looks like a whole number.
Note: Math functions expect their arguments as doubles. Passing 16 (an int) usually works because C converts it, but writing 16.0 makes your intent clear and avoids surprises.

Exercise: C Math Functions

Which header must be included to use functions like sqrt() and pow()?