Explain it simply
Explain it simply
<math.h> is like a scientific calculator that ships with C. It already has buttons for square roots (sqrt), powers (pow), rounding (round, floor, ceil) and trigonometry (sin, cos), so you never have to code those formulas yourself.
Its one quirk is that every answer comes back as a double, a number with a fractional part. Even the 16 from pow(4, 2) is really the double 16.0, so you print results with %f or %.2f, never with %d.
Problem → Why → Solution
The problem: it compiles, but every answer is wrong
Compiled with plain gcc and no flags, the program below builds without a single warning. Run on Windows with GCC 16, it prints 3.00 instead of 3.75, 0 instead of 1024, and 1.000 instead of 1.414. Each of the three lines hides a type mistake.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
double change = -3.75;
double size = abs(change); /* wanted 3.75, got 3.00 */
printf("%.2f\n", size);
printf("%d\n", pow(2, 10)); /* wanted 1024, got 0 */
printf("%.3f\n", pow(2, 1 / 2)); /* wanted 1.414, got 1.000 */
return 0;
}Why are they wrong?
abs() works on int, so -3.75 is truncated to -3 before the absolute value is taken. pow() returns a double, but %d expects an int, which is undefined behaviour. And 1 / 2 is integer division, so it is 0, and pow(2, 0) is 1. With -Wall -Wextra, GCC warns about the first two; the third you have to spot yourself.
Core concept: double in, double out
Most <math.h> prototypes look like double sqrt(double x);. Thanks to the prototype, an int argument is converted to double automatically, so sqrt(16) is fine. That conversion only happens at the call, though: an int expression inside the parentheses, such as the 1 / 2 in pow(2, 1 / 2), has already been computed as an int. There are also float and long double variants such as sqrtf and sqrtl. Storing a result in an int, as in int side = sqrt(10.0);, silently drops the fractional part, so keep results in double until you deliberately round them.
Because results are doubles, print them with %f. Plain %f shows six decimal places, and %.2f rounds the displayed value to two; that changes only what is printed, not the value in memory. printf converts float arguments to double as well, so %f covers both. When you need a whole number, convert explicitly, for example with lround(), which returns a long.
The four rounding functions differ most clearly on negative numbers: floor(-2.5) is -3, ceil(-2.5) is -2, trunc(-2.5) is -2, and round(-2.5) is -3, because round sends halves away from zero. For absolute values, use fabs() for doubles and abs() from <stdlib.h> for ints.
With glibc on Linux, the math functions live in a separate library, libm, so you add -lm after your source files: gcc main.c -o app -lm. The compiler can precompute calls with constant arguments such as sqrt(16.0), so a program sometimes links without -lm and then fails as soon as a call uses a variable. Always add it. macOS and Windows MinGW do not need it, but accept it harmlessly.
- Arguments are converted to double
- The math.h function computes in double
- The result is a double, maybe NaN/inf
- Print with %.2f or convert with lround
Integer expressions inside the parentheses are evaluated as ints before any conversion happens.
General pattern
#include <math.h>
double result = function_name(double_argument);
printf("%.2f\n", result); /* 2 decimal places */
/* build on Linux: libraries go after the source files */
/* gcc file.c -o app -lm */Include <math.h>, store the result in a double, and print it with the %f family. Put -lm at the end of the build command.
Example: the everyday math functions
This program compares the rounding functions on a negative number, then computes the distance between two points and savings growing 5% a year. Compare each format string with the output to see how it controls the number of decimal places.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
printf("sqrt(16.0) = %.1f\n", sqrt(16.0));
printf("pow(4, 2) = %.0f\n", pow(4, 2));
printf("round(2.6) = %.0f\n", round(2.6));
printf("floor(-2.5) = %.0f\n", floor(-2.5));
printf("ceil(-2.5) = %.0f\n", ceil(-2.5));
printf("fabs(-3.75) = %.2f\n", fabs(-3.75));
printf("abs(-7) = %d\n", abs(-7));
double x1 = 1.0, y1 = 2.0, x2 = 4.0, y2 = 6.0;
double distance = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
printf("distance = %.2f\n", distance);
double savings = 1000.0 * pow(1.05, 10); /* 5% a year, 10 years */
printf("savings = %.2f\n", savings);
return 0;
}Code breakdown
- Integer arguments
printf("pow(4, 2) = %.0f\n", pow(4, 2));4 and 2 are ints, but the prototype converts them to double. The result 16.0 is a double, so %.0f prints it with no decimals.
- Rounding down and up
printf("floor(-2.5) = %.0f\n", floor(-2.5));floor moves left on the number line, towards smaller values, so -2.5 becomes -3. ceil on the next line moves right and gives -2.
- Two absolute values
printf("fabs(-3.75) = %.2f\n", fabs(-3.75));fabs takes a double and keeps the full 3.75. On the next line, abs(-7) is the int version, printed with %d.
- Distance formula
double distance = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));The Pythagorean formula: dx is 3 and dy is 4, so sqrt(9 + 16) is 5. hypot(x2 - x1, y2 - y1) from math.h does the same job with less risk of overflow.
- Compound growth
double savings = 1000.0 * pow(1.05, 10); /* 5% a year, 10 years */Multiplies by 1.05 ten times. The real value is 1628.894626..., and %.2f rounds it to 1628.89 only when printing.
sqrt(16.0) = 4.0
pow(4, 2) = 16
round(2.6) = 3
floor(-2.5) = -3
ceil(-2.5) = -2
fabs(-3.75) = 3.75
abs(-7) = 7
distance = 5.00
savings = 1628.89A quick reference table
| Function | What it does | Example |
|---|---|---|
| sqrt(x) | Square root (x >= 0) | sqrt(2.0) → 1.414... |
| pow(x, y) | x raised to the power y | pow(2, 0.5) → 1.414... |
| fabs(x) | Absolute value of a double | fabs(-0.5) → 0.5 |
| floor / ceil | Next whole number down / up | ceil(4.1) → 5.0 |
| round / trunc | Nearest / drop the fraction | trunc(-4.9) → -4.0 |
| fmod(x, y) | Remainder for doubles | fmod(7.5, 2) → 1.5 |
| sin / cos / tan | Trigonometry in radians | cos(0) → 1.0 |
| log / log10 / exp | Natural log, base-10 log, e^x | log10(1000) → 3.0 |
Printing and comparing floating-point values
Doubles are stored as binary fractions, so most decimal values, 0.1 included, cannot be stored exactly. 0.1 + 0.2 prints as 0.30 with %.2f, yet its real value is 0.30000000000000004, so == 0.3 is false. 2.675 is stored as 2.67499999..., so %.2f prints 2.67, not 2.68. Compare with fabs(a - b) < tolerance instead.
#include <math.h>
#include <stdio.h>
int main(void) {
double total = 0.1 + 0.2;
printf("2 places: %.2f\n", total);
printf("17 places: %.17f\n", total);
printf("total == 0.3? %s\n", total == 0.3 ? "yes" : "no");
printf("within 1e-9? %s\n", fabs(total - 0.3) < 1e-9 ? "yes" : "no");
printf("2.675 shown with 2 places: %.2f\n", 2.675);
return 0;
}An input with no real answer, such as sqrt(-1.0), is a domain error and returns NaN (not a number). A pole error such as log(0.0) returns infinity. Depending on the C library, printf shows NaN as nan, -nan or similar, so test with isnan(), isinf() and isfinite() instead of looking at the text.
#include <math.h>
#include <stdio.h>
int main(void) {
double root = sqrt(-1.0); /* domain error: no real answer */
double logarithm = log(0.0); /* pole error: minus infinity */
if (isnan(root)) {
printf("sqrt(-1.0) is NaN (not a number)\n");
}
if (isinf(logarithm) && logarithm < 0) {
printf("log(0.0) is negative infinity\n");
}
printf("isfinite(sqrt(2.0)): %s\n", isfinite(sqrt(2.0)) ? "yes" : "no");
return 0;
}In real projects
Where this shows up in real projects
Game engines compute distances between objects with sqrt and hypot, and directions and rotations with sin, cos and atan2. Embedded programs that read sensors summarise the values with averages and standard deviations (sqrt again) and show them with %.1f on a display. The haversine formula behind GPS distance calculations combines sin, cos, asin and sqrt.
Financial software usually avoids double for money altogether and stores amounts as integer cents, because surprises like 0.1 + 0.2 are unacceptable in accounting. Scientific and engineering code, on the other hand, checks intermediate results with isfinite(), since a single NaN silently spreads through every calculation that touches it. Graphics code often goes the other way and prefers float with the f-suffixed functions such as sqrtf, trading precision for speed and memory.
Common mistakes
Common mistakes
1. Calling abs() on a double
abs(-3.75) truncates its argument to an int and returns just 3. With -Wextra, GCC warns "using integer absolute value function 'abs' when argument is of floating-point type 'double'". Use fabs() for doubles and fabsf() for floats.
2. Printing pow()'s result with %d
printf("%d", pow(2, 10)) is undefined behaviour; a GCC 16 build on Windows printed 0. -Wall reports "format '%d' expects argument of type 'int', but argument 2 has type 'double'". Print with %.0f, or convert with lround() when you need an integer.
3. Integer division hiding inside an argument
In pow(2, 1 / 2), 1 / 2 divides two ints and yields 0, so the result is 1.000, and the compiler gives no warning. Write 1.0 / 2, or for a square root simply call sqrt(2.0).
4. Passing degrees to sin() and cos()
sin(90) is 0.8940, not 1, because the trig functions expect radians. Convert with degrees * PI / 180.0. M_PI is not standard C, and gcc -std=c17 can reject it with "'M_PI' undeclared", so declare your own PI constant.
Best practices
Best practices
- Compile with -Wall -Wextra and end every Linux build command with -lm.
- Keep math results in double variables and round only when printing, with %.2f.
- Never compare floating-point values with ==; use a tolerance.
- Check results with isfinite() whenever they are computed from outside data.
Mini challenge
Mini challenge: four geometry helpers
Use <math.h> to write four helper functions and print their results in main() with the right number of decimal places.
- double distance(double x1, double y1, double x2, double y2) uses hypot() or sqrt()
- double round_to(double value, int places) uses pow(10.0, places) and round()
- int nearly_equal(double a, double b, double tolerance) uses fabs(), never ==
- double deg_to_rad(double degrees) uses your own PI constant, not M_PI
#include <math.h>
#include <stdio.h>
static const double PI = 3.14159265358979323846;
double distance(double x1, double y1, double x2, double y2) {
// TODO: length of the line between the two points
return 0.0;
}
double round_to(double value, int places) {
// TODO: scale by 10^places, round, scale back
return value;
}
int nearly_equal(double a, double b, double tolerance) {
// TODO: compare the absolute difference with tolerance
return 0;
}
double deg_to_rad(double degrees) {
// TODO: convert using PI
return degrees;
}
int main(void) {
// TODO: distance (0,0)-(1,1), round_to(3.14159, 3),
// 0.1 + 0.2 vs 0.3 with == and with nearly_equal,
// sin of 30 degrees
return 0;
}Expected: The program prints: distance (0,0)-(1,1) = 1.41 round_to(3.14159, 3) = 3.142 0.1 + 0.2 == 0.3: no nearly_equal(0.1 + 0.2, 0.3): yes sin(30 degrees) = 0.50
Show hint
In round_to(), compute factor = pow(10.0, places) and return round(value * factor) / factor. sin(deg_to_rad(30.0)) comes out near 0.49999999999999994, which %.2f prints as 0.50.
Show solution
#include <math.h>
#include <stdio.h>
static const double PI = 3.14159265358979323846; /* M_PI is not standard C */
double distance(double x1, double y1, double x2, double y2) {
return hypot(x2 - x1, y2 - y1);
}
double round_to(double value, int places) {
double factor = pow(10.0, places);
return round(value * factor) / factor;
}
int nearly_equal(double a, double b, double tolerance) {
return fabs(a - b) <= tolerance;
}
double deg_to_rad(double degrees) {
return degrees * PI / 180.0;
}
int main(void) {
printf("distance (0,0)-(1,1) = %.2f\n", distance(0.0, 0.0, 1.0, 1.0));
printf("round_to(3.14159, 3) = %.3f\n", round_to(3.14159, 3));
printf("0.1 + 0.2 == 0.3: %s\n", (0.1 + 0.2 == 0.3) ? "yes" : "no");
printf("nearly_equal(0.1 + 0.2, 0.3): %s\n",
nearly_equal(0.1 + 0.2, 0.3, 1e-9) ? "yes" : "no");
printf("sin(30 degrees) = %.2f\n", sin(deg_to_rad(30.0)));
return 0;
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- <math.h> functions take and return double, so print results with %f or %.2f, never %d.
- Use fabs() for doubles and abs() for ints, and watch for integer division inside arguments.
- With glibc on Linux, put -lm after your source files.
- Compare floating-point values with a tolerance and detect NaN and infinity with isnan(), isinf() and isfinite().
GNU C compiler diagnostics — GNU Project