← Back to C Course | Chapter 5: Functions | Lesson 8 of 8

C Math Functions

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

c
#include <stdio.h>
#include <math.h>
int main() {
	printf("%.2f", sqrt(16.0));
	return 0;
}

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)

c
#include <stdio.h>
#include <math.h>
int main() {
	printf("%.2f", sqrt(25.0));
	return 0;
}

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)

c
#include <stdio.h>
#include <math.h>
int main() {
	printf("%.1f", pow(2.0, 3.0));
	return 0;
}

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)

c
#include <stdio.h>
#include <math.h>
int main() {
	printf("%.1f %.1f", ceil(4.1), floor(4.9));
	return 0;
}

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)

c
#include <stdio.h>
#include <math.h>
int main() {
	printf("%.1f", fabs(-7.5));
	return 0;
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.