C Math Functions
The <math.h> header provides a library of mathematical functions like square root, power, absolute value, trigonometric functions and more, that go beyond basic arithmetic operators.
When compiling on Linux with GCC, you may need to link the math library explicitly using the -lm flag.
#include <math.h>
sqrt(x); pow(x, y);Common functions
sqrt() computes a square root, pow(base, exp) raises a number to a power, fabs() returns the absolute value of a double, and floor()/ceil() round down or up.
Linking the math library
On some systems, using math.h functions requires compiling with `gcc file.c -o file -lm` so the linker can find the math library's implementation.
#include <stdio.h>
#include <math.h>
int main() {
printf("%.2f\n", sqrt(16.0));
return 0;
}4.00sqrt(16.0) computes the square root of 16, which is 4.
#include <stdio.h>
#include <math.h>
int main() {
printf("%.1f\n", pow(2.0, 3.0));
return 0;
}8.0pow(2.0, 3.0) raises 2 to the power of 3, giving 8.
Key points
- Include <math.h> to access sqrt, pow, fabs and more.
- Math functions typically work with double values.
- On Linux/GCC you may need to add -lm when compiling.
- floor() rounds down and ceil() rounds up to the nearest integer.
