C Math Functions
In this page:
Including math.h
Every function in math.h operates on floating-point numbers and requires you to link the math library at compile time (with -lm on most Unix compilers). Forgetting the header leaves you with implicit-declaration warnings and undefined behavior on some platforms.
Example: Including math.h
#include <stdio.h>
#include <math.h>
int main() {
printf("%.2f", sqrt(16.0));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Square Root (sqrt)
sqrt() only accepts non-negative arguments -- passing a negative number produces NaN rather than a compile error, so validating input before calling it is good practice. It's commonly used for distance formulas and statistical calculations like standard deviation.
Example: Square Root (sqrt)
#include <stdio.h>
#include <math.h>
int main() {
printf("%.2f", sqrt(25.0));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Power Function (pow)
Unlike the exponent operator in languages such as Python, C has no ** syntax, so pow(base, exponent) is the only built-in way to raise a number to a power. Both arguments and the return value are doubles, even when you're working with whole numbers.
Example: Power Function (pow)
#include <stdio.h>
#include <math.h>
int main() {
printf("%.1f", pow(2.0, 3.0));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Rounding Functions (ceil and floor)
ceil(4.1) returns 5.0 while floor(4.9) returns 4.0 -- both always move away from or toward zero along the number line rather than rounding to the nearest integer. They're essential when you need predictable rounding behavior, such as computing how many pages a printout needs.
Example: Rounding Functions (ceil and floor)
#include <stdio.h>
#include <math.h>
int main() {
printf("%.1f %.1f", ceil(4.1), floor(4.9));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Absolute Value (fabs)
fabs() is the floating-point counterpart to abs(), which only works on integers; using abs() on a double silently truncates it before taking the absolute value, a common source of subtle bugs. Use fabs() whenever you're comparing floating-point differences against a tolerance.
Example: Absolute Value (fabs)
#include <stdio.h>
#include <math.h>
int main() {
printf("%.1f", fabs(-7.5));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: