C Math Functions
The header math.h contains the functions of mathematics: square roots, powers, rounding and trigonometry. They work with double values. On many systems the math library must be linked with -lm (gcc main.c -lm); our editor does that for you.
Common functions
| Function | Result |
|---|---|
sqrt(x) | square root of x |
pow(x, y) | x to the power y |
fabs(x) | absolute value of a double |
ceil(x) | rounds up to a whole number |
floor(x) | rounds down to a whole number |
round(x) | rounds to the nearest whole number |
fmod(x, y) | remainder of x / y for decimals |
sin(x), cos(x), tan(x) | trigonometry, x in radians |
log(x), log10(x), exp(x) | natural log, base-10 log, e to the x |
ExampleTry it in the editor
#include <math.h>
#include <stdio.h>
int main(void) {
printf("sqrt(64) = %.1f\n", sqrt(64));
printf("pow(2, 10) = %.0f\n", pow(2, 10));
printf("fabs(-4.5) = %.1f\n", fabs(-4.5));
printf("ceil(4.2) = %.0f\n", ceil(4.2));
printf("floor(4.8) = %.0f\n", floor(4.8));
printf("round(4.5) = %.0f\n", round(4.5));
printf("log10(1000) = %.0f\n", log10(1000));
return 0;
}Output
sqrt(64) = 8.0 pow(2, 10) = 1024 fabs(-4.5) = 4.5 ceil(4.2) = 5 floor(4.8) = 4 round(4.5) = 5 log10(1000) = 3
For integers, abs(n) from stdlib.h gives the absolute value; fabs is for decimals.
A practical example: the hypotenuse
ExampleTry it in the editor
#include <math.h>
#include <stdio.h>
int main(void) {
double a = 3, b = 4;
double c = sqrt(a * a + b * b);
printf("The hypotenuse is %.1f\n", c);
return 0;
}Output
The hypotenuse is 5.0
Angles are in radians
The trigonometric functions use radians, not degrees. To convert, multiply by π / 180. C does not guarantee a constant for π, so define one:
ExampleTry it in the editor
#include <math.h>
#include <stdio.h>
#define PI 3.14159265358979
int main(void) {
double degrees = 30;
double radians = degrees * PI / 180;
printf("sin(30 degrees) = %.2f\n", sin(radians));
printf("cos(60 degrees) = %.2f\n", cos(60 * PI / 180));
return 0;
}Output
sin(30 degrees) = 0.50 cos(60 degrees) = 0.50
Decimal numbers are not exact
A double cannot store most decimal fractions exactly: 0.1 + 0.2 is very slightly more than 0.3. So never compare decimals with ==; check that the difference is tiny instead: fabs(a - b) < 1e-9.
Practice exercises
- Compute the area of a circle with radius 5 using
PIandpow. - Read a number and print its square root, or a message if it is negative.
- Print 0.1 + 0.2 with 20 decimals, then compare it with 0.3 using
==and usingfabs. - Compute compound interest: 1000 at 7% per year for 10 years is 1000 × 1.07^10.