Ready-Made Maths: math.h

For harder maths, C has a toolbox called math.h. Include it at the top:

FunctionWhat it doesExampleResult
sqrt(x)Square rootsqrt(25)5
pow(x, y)x to the power of ypow(2, 10)1024
fabs(x)Remove the minus signfabs(-3.5)3.5
round(x)Round to nearest wholeround(2.6)3
floor(x)Round downfloor(2.9)2
ceil(x)Round upceil(2.1)3
#include <stdio.h>
#include <math.h>

int main() {
    printf("%.1f\n", sqrt(25.0));
    printf("%.0f\n", pow(2, 10));
    printf("%.1f\n", fabs(-3.5));
    printf("%.0f %.0f %.0f\n", round(2.6), floor(2.9), ceil(2.1));
    return 0;
}

Output

5.0
1024
3.5
3 2 3

All of these give back a double, so print them with %f (or %.0f for no decimals).

Example: area of a circle

#include <stdio.h>
#include <math.h>

#define PI 3.14159265

int main() {
    double radius;
    scanf("%lf", &radius);
    printf("Area: %.2f\n", PI * pow(radius, 2));
    return 0;
}

Input (what the user types)

3

Output

Area: 28.27

Tip: On your own computer, add -lm when you compile a program that uses math.h: gcc circle.c -o circle -lm.

Remember: #include <math.h> gives you sqrt, pow, fabs, round, floor and ceil.

HOME LABS COMMUNITY DASHBOARD