
Math Functions in C
? Math Functions in C
C provides a set of built-in math functions through the math.h
header file. These functions handle everything from basic math to trigonometry and logarithms.
? First: Include the Header
Function Description Example Result sqrt(x)
Square root sqrt(16)
4.0
pow(x, y)
x raised to the power y pow(2, 3)
8.0
abs(x)
Absolute value (for int
) abs(-5)
5
fabs(x)
Absolute value (for float/double
) fabs(-5.5)
5.5
ceil(x)
Round up to nearest int ceil(4.2)
5.0
floor(x)
Round down to nearest int floor(4.9)
4.0
round(x)
Round to nearest int round(4.5)
5.0
log(x)
Natural log (base e) log(2.71828)
? 1.0
log10(x)
Log base 10 log10(1000)
3.0
sin(x)
Sine (radians) sin(M_PI/2)
1.0
cos(x)
Cosine (radians) cos(0)
1.0
tan(x)
Tangent (radians) tan(M_PI/4)
1.0
? Example Program
#include #include <math.h>int main() { double x = 9.0; printf("Square root of %.2f = %.2f\n", x, sqrt(x)); printf("Power of 2^3 = %.2f\n", pow(2, 3)); printf("Ceil of 4.3 = %.2f\n", ceil(4.3)); printf("Floor of 4.7 = %.2f\n", floor(4.7)); printf("Absolute of -10 = %d\n", abs(-10)); return 0;}
?? Notes
Use
gcc -lm file.c
when compiling — the-lm
flag links the math library.Angles for
sin
,cos
,tan
are in radians, not degrees!