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.0Common 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.
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.
Exercise: C Math Functions
Which header must be included to use functions like sqrt() and pow()?