Learn C
#include "stdlib/math_lib.h"

Math with math.h in C

#concept

math.h covers roots and powers (sqrt, pow, cbrt), rounding (floor, ceil, round, trunc), trigonometry (sin, cos, tan plus asin/acos/atan2), exponentials and logs (exp, log, log10), and remainders (fmod — % doesn't work on doubles). Angles arrive in radians; constants like M_PI need _GNU_SOURCE or _USE_MATH_DEFINES depending on platform.

Linking math is a separate step on GCC/Clang: append -lm (libm) or face undefined reference to sqrt. Float comparisons need epsilon checks, and domain errors (sqrt(-1)) set errno (EDOM) and return NaN rather than crashing.

#how it works
1

Link with -lm

gcc app.c -lm — math lives in a separate library on Unix-likes; forgetting -lm is the classic undefined reference to sqrt.

2

Roots, powers, rounding

sqrt/pow/cbrt compute; floor/ceil/round/trunc quantize differently — round() halves away from zero, trunc() toward it.

3

Trig in radians

sin/cos/tan take radians; atan2(y, x) recovers full-circle angles correctly where atan cannot.

4

Errors set errno

sqrt(-1) returns NaN and sets EDOM — check errno or isnan() instead of expecting a crash.

#example
#include <stdio.h>
#include <math.h>
 
int main(void) {
printf("%.2f\n", sqrt(2.0));
printf("%.0f\n", pow(2.0, 10.0));
printf("%.0f\n", floor(3.9));
return 0;
}
Output
1.41
1024
3
1sqrt(2.0) computes the irrational root, rounded by %.2f to 1.41.
2pow(2.0, 10.0) is exact at 1024 — floating math, integer-valued result.
3floor always rounds down, so 3.9 becomes 3.
#use cases
Remembering -lm on every GCC/Clang math build
Rounding modes (floor vs round vs trunc) chosen per domain
atan2 for correct quadrant-aware angle recovery
errno/NaN checks on domain-edge computations

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.