Math with math.h in C
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.
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.
Roots, powers, rounding
sqrt/pow/cbrt compute; floor/ceil/round/trunc quantize differently — round() halves away from zero, trunc() toward it.
Trig in radians
sin/cos/tan take radians; atan2(y, x) recovers full-circle angles correctly where atan cannot.
Errors set errno
sqrt(-1) returns NaN and sets EDOM — check errno or isnan() instead of expecting a crash.
#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;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.