The standard header <math.h> gives C programs a full scientific calculator: powers and roots, four kinds of rounding, logarithms, trigonometry and checks for special values such as “not a number”. This lesson tours the functions you will use most, explains the difference between round, floor, ceil and trunc, and shows two details that trip up beginners: linking with -lm and comparing floating-point results.
In this lesson you will learn
pow,sqrt,cbrt,fabsandhypot- The four rounding functions and how they treat negative numbers
- Exponentials, logarithms and
fmod - Trigonometry in radians and computing π
- Comparing doubles safely and detecting NaN and infinity
You should know data types and operators.
Powers, Roots and Rounding
#include <math.h>
#include <stdio.h>
int main(void) {
/* Powers, roots and absolute values (link with -lm on Linux) */
printf("pow(2, 10) = %.0f, sqrt(2) = %.4f, cbrt(27) = %.1f\n", pow(2, 10), sqrt(2), cbrt(27));
printf("fabs(-3.5) = %.1f, hypot(3, 4) = %.1f\n", fabs(-3.5), hypot(3, 4));
/* Rounding: four different rules */
double vals[] = {2.5, -2.5, 3.7, -3.7};
printf("%6s %6s %6s %6s %6s\n", "x", "round", "floor", "ceil", "trunc");
for (int i = 0; i < 4; i++) {
double x = vals[i];
printf("%6.1f %6.1f %6.1f %6.1f %6.1f\n", x, round(x), floor(x), ceil(x), trunc(x));
}
/* Exponentials and logarithms */
printf("exp(1) = %.5f, log(e) = %.1f, log10(1000) = %.1f, log2(1024) = %.1f\n",
exp(1), log(exp(1)), log10(1000), log2(1024));
/* Remainder of floating-point division */
printf("fmod(10.5, 3) = %.1f\n", fmod(10.5, 3));
return 0;
}
Output
pow(2, 10) = 1024, sqrt(2) = 1.4142, cbrt(27) = 3.0
fabs(-3.5) = 3.5, hypot(3, 4) = 5.0
x round floor ceil trunc
2.5 3.0 2.0 3.0 2.0
-2.5 -3.0 -3.0 -2.0 -2.0
3.7 4.0 3.0 4.0 3.0
-3.7 -4.0 -4.0 -3.0 -3.0
exp(1) = 2.71828, log(e) = 1.0, log10(1000) = 3.0, log2(1024) = 10.0
fmod(10.5, 3) = 1.5
- Most
math.hfunctions take and returndouble. Versions ending infandl, such assqrtfandsqrtl, work onfloatandlong double. - On Linux, add
-lmwhen compiling (gcc prog.c -lm) to link the maths library; otherwise you may get “undefined reference to pow”. hypot(3, 4)computes √(3² + 4²) = 5 without overflowing for very large values.roundgoes to the nearest whole number, with halves going away from zero (2.5 → 3, -2.5 → -3).flooralways goes down,ceilalways up, andtruncsimply drops the fraction, which goes toward zero. The four only agree for positive numbers that are not exactly halfway.logis the natural logarithm (base e);log10andlog2use bases 10 and 2.fmodis the remainder for floating-point numbers, since the%operator works only on integers.
Trigonometry and Practical Calculations
#include <math.h>
#include <stdio.h>
int main(void) {
const double PI = acos(-1.0); /* M_PI is not part of standard C */
/* Trigonometry works in radians */
double deg = 30;
double rad = deg * PI / 180;
printf("sin(30 deg) = %.3f, cos(60 deg) = %.3f, tan(45 deg) = %.3f\n",
sin(rad), cos(60 * PI / 180), tan(45 * PI / 180));
printf("atan2(1, 1) = %.1f degrees\n", atan2(1, 1) * 180 / PI);
/* Compound interest: 10000 taka at 8% for 5 years */
double amount = 10000 * pow(1 + 0.08, 5);
printf("after 5 years: %.2f taka\n", amount);
/* Distance between two points */
double x1 = 1, y1 = 2, x2 = 4, y2 = 6;
printf("distance = %.1f\n", hypot(x2 - x1, y2 - y1));
/* Comparing floating-point numbers needs a tolerance */
double a = 0.1 + 0.2;
printf("0.1 + 0.2 == 0.3? %s; within 1e-9? %s\n",
a == 0.3 ? "yes" : "no", fabs(a - 0.3) < 1e-9 ? "yes" : "no");
/* Special values */
double bad = sqrt(-1.0);
double big = exp(1000);
printf("sqrt(-1) is NaN: %d, exp(1000) is infinite: %d\n", isnan(bad) != 0, isinf(big) != 0);
return 0;
}
Output
sin(30 deg) = 0.500, cos(60 deg) = 0.500, tan(45 deg) = 1.000
atan2(1, 1) = 45.0 degrees
after 5 years: 14693.28 taka
distance = 5.0
0.1 + 0.2 == 0.3? no; within 1e-9? yes
sqrt(-1) is NaN: 1, exp(1000) is infinite: 1
- Trigonometric functions use radians. Convert degrees with
deg * PI / 180. - Standard C does not define
M_PI; many systems provide it, butacos(-1.0)gives π portably. atan2(y, x)returns the angle of the point (x, y), handling all four quadrants correctly, unlikeatan(y / x).- Compound interest is
principal × (1 + rate)years, a direct use ofpow: 10,000 taka at 8% grows to 14,693.28 taka in five years. - 0.1 + 0.2 is not exactly 0.3 in binary floating point, so
==fails. Compare the difference against a small tolerance withfabs. - Invalid operations return special values instead of crashing:
sqrt(-1)gives NaN (“not a number”) andexp(1000)gives infinity. Test for them withisnanandisinf.
math.h Cheat Sheet
| Function | Returns | Example |
|---|---|---|
pow(x, y) | xy | pow(2, 8) = 256 |
sqrt(x), cbrt(x) | Square root, cube root | sqrt(81) = 9 |
fabs(x) | Absolute value of a double | fabs(-2.5) = 2.5 |
round, floor, ceil, trunc | Rounded values | ceil(2.1) = 3 |
exp(x), log(x) | ex, natural log | log(1) = 0 |
log10(x), log2(x) | Base-10 and base-2 logs | log2(8) = 3 |
sin, cos, tan | Trigonometry (radians) | cos(0) = 1 |
asin, acos, atan, atan2 | Inverse trigonometry | acos(-1) = π |
fmod(x, y) | Floating remainder | fmod(7.5, 2) = 1.5 |
hypot(x, y) | √(x² + y²) | hypot(5, 12) = 13 |
The integer absolute value is abs in <stdlib.h>; calling abs on a double converts it to int first and loses the fraction.
Common Mistakes
- Forgetting
-lmwhen linking on Linux. - Passing degrees to
sinandcos. - Using
pow(x, 2)in tight loops wherex * xis simpler and faster. - Printing a
doublewith%d, which prints garbage. Use%f,%.2for%g.
Practice Exercises
Exercise 1. Compute the area of a circle of radius 7, rounded to two decimal places.
Show answer
double r = 7, area = acos(-1.0) * r * r;
printf("%.2f\n", area); /* 153.94 */
Exercise 2. How many pages of 25 rows are needed for 213 rows? Use a math.h function.
Show answer
int pages = (int)ceil(213 / 25.0); /* 9 */
Note the 25.0; with 213 / 25 the integer division would happen first and give 8. The integer-only alternative is (213 + 24) / 25.
Frequently Asked Questions
Why does round(2.5) give 3 but printf(“%.0f”, 2.5) print 2?
round always rounds halves away from zero. printf follows the current floating-point rounding mode, normally “round half to even”, so with the GNU C library 2.5 prints as 2 and 3.5 as 4. Some other C libraries print 3 for 2.5, so use round when the result matters.
How do I get random numbers in C?
Random numbers come from <stdlib.h>, not math.h: call srand once with a seed, then rand() % n for a value from 0 to n − 1. For security purposes, use your operating system’s secure random source instead.
Summary
- Include
<math.h>and link with-lmon Linux. round,floor,ceilandtruncdiffer for negatives and halves.- Trigonometry uses radians;
acos(-1.0)gives π portably. - Compare doubles with a tolerance and check for NaN and infinity.
Next: Undefined Behaviour in C.
