The <math.h> library in C provides a collection of functions that allow you to perform mathematical operations on floating-point numbers. Whether you are building a scientific calculator, a game engine, or a data analysis tool, these functions are indispensable.
Most math functions in C return a double value, even if you pass an int as an argument. To use them, always include the library:
Here are the most frequently used functions that every C developer should know:
x.x raised to the power of y ($x^y$).x up to the nearest integer.x down to the nearest integer.<stdlib.h>). Use fabs(x) for floating-point numbers.C also provides a full suite of trigonometric functions. **Note:** These functions expect the input angle to be in radians, not degrees.
| Function | Input Type | Result for 4.6 |
|---|---|---|
ceil() |
double | 5.0 |
floor() |
double | 4.0 |
round() |
double | 5.0 |
If you are compiling your C program via the terminal (using GCC) on a Unix-based system, you must manually link the math library using the -lm flag. Otherwise, you will see an "undefined reference to sqrt" error.
pow(x, y), remember that floating-point math can sometimes have tiny precision errors. For simple integer squaring, x * x is much faster and more accurate than pow(x, 2).