Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

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

FunctionResult
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
#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

#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:

#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

  1. Compute the area of a circle with radius 5 using PI and pow.
  2. Read a number and print its square root, or a message if it is negative.
  3. Print 0.1 + 0.2 with 20 decimals, then compare it with 0.3 using == and using fabs.
  4. Compute compound interest: 1000 at 7% per year for 10 years is 1000 × 1.07^10.