Reading history

math.h Functions in C: pow, sqrt, round and More

5 min read 1 views

Use C math.h functions: pow, sqrt, hypot, round vs floor vs ceil vs trunc, logarithms, trigonometry in radians, comparing doubles and NaN checks.

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, fabs and hypot
  • 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.h functions take and return double. Versions ending in f and l, such as sqrtf and sqrtl, work on float and long double.
  • On Linux, add -lm when 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.
  • round goes to the nearest whole number, with halves going away from zero (2.5 → 3, -2.5 → -3). floor always goes down, ceil always up, and trunc simply drops the fraction, which goes toward zero. The four only agree for positive numbers that are not exactly halfway.
  • log is the natural logarithm (base e); log10 and log2 use bases 10 and 2.
  • fmod is 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, but acos(-1.0) gives π portably.
  • atan2(y, x) returns the angle of the point (x, y), handling all four quadrants correctly, unlike atan(y / x).
  • Compound interest is principal × (1 + rate)years, a direct use of pow: 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 with fabs.
  • Invalid operations return special values instead of crashing: sqrt(-1) gives NaN (“not a number”) and exp(1000) gives infinity. Test for them with isnan and isinf.

math.h Cheat Sheet

FunctionReturnsExample
pow(x, y)xypow(2, 8) = 256
sqrt(x), cbrt(x)Square root, cube rootsqrt(81) = 9
fabs(x)Absolute value of a doublefabs(-2.5) = 2.5
round, floor, ceil, truncRounded valuesceil(2.1) = 3
exp(x), log(x)ex, natural loglog(1) = 0
log10(x), log2(x)Base-10 and base-2 logslog2(8) = 3
sin, cos, tanTrigonometry (radians)cos(0) = 1
asin, acos, atan, atan2Inverse trigonometryacos(-1) = π
fmod(x, y)Floating remainderfmod(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

  1. Forgetting -lm when linking on Linux.
  2. Passing degrees to sin and cos.
  3. Using pow(x, 2) in tight loops where x * x is simpler and faster.
  4. Printing a double with %d, which prints garbage. Use %f, %.2f or %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 -lm on Linux.
  • round, floor, ceil and trunc differ 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.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *