HOME HTML EDITOR C JAVA PHP

C Math Functions: Powering Complex Calculations

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.

1. The math.h Header

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:

#include <math.h>

2. Common Mathematical Functions

Here are the most frequently used functions that every C developer should know:

Example Usage:

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

int main() {
    printf("Square root of 16: %.1f\n", sqrt(16));
    printf("2 to the power 3: %.1f\n", pow(2, 3));
    printf("Ceil of 4.3: %.1f\n", ceil(4.3));
    printf("Floor of 4.7: %.1f\n", floor(4.7));
    return 0;
}

3. Trigonometric Functions

C also provides a full suite of trigonometric functions. **Note:** These functions expect the input angle to be in radians, not degrees.

printf("Sine of 0: %.1f\n", sin(0));
printf("Cosine of 0: %.1f\n", cos(0));
printf("Tangent of 45 deg: %.1f\n", tan(45 * 3.14159 / 180));

4. Quick Reference Table

Function Input Type Result for 4.6
ceil() double 5.0
floor() double 4.0
round() double 5.0

5. Critical Linker Note (Linux/macOS)

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.

gcc main.c -o main -lm
Pro Tip: When working with 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).