Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 171 Β· Variables and Types

Math Functions

Use C++ math functions from <cmath> and <numeric>, pow, sqrt, rounding, trig, gcd, lcm, std::numbers, and integer division and remainder with negatives.

Sooner or later every program needs more than + and -. A game needs the distance between two points, a shop needs to round prices, a scheduler needs the greatest common divisor of two periods. C++ ships all of this in its standard library, so you never have to write your own square root.

In this lesson you will tour the math toolbox: powers and roots from <cmath>, the different ways to round, trigonometry with std::numbers::pi, gcd, lcm and midpoint from <numeric>, and how integer division and % behave with negative numbers, which surprises people coming from Python.

Where the math functions live

The functions are spread over a few headers. You will use these most:

Header What it gives you
<cmath> pow, sqrt, cbrt, hypot, abs, round, floor, ceil, trunc, sin, cos, atan2, exp, log, fmod, isnan, …
<numeric> gcd, lcm, midpoint (plus algorithms like accumulate)
<numbers> constants: std::numbers::pi, e, sqrt2, phi, … (C++20)
<algorithm> std::min, std::max, std::clamp
<cstdlib> std::abs for integers (also available through <cmath>)

Everything is in the std namespace. Older code often includes <math.h> and calls sqrt without std::. That still compiles, but it is the C header, and some of the C++ overloads (for float and integer arguments) may be missing. Include <cmath> and write std::sqrt.

Most <cmath> functions work with double. They also have float and long double overloads, and if you pass an integer it is converted to double first. So std::sqrt(16) returns the double value 4, not the int 4.

Powers and roots

std::pow(base, exponent) raises a number to a power, std::sqrt takes the square root, and std::cbrt the cube root. std::hypot(x, y) returns the length of the hypotenuse, √(x² + y²), and it avoids overflow for very large inputs that would break the naive formula.

C++ Powers, roots and distances

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

A few habits professionals follow:

  • Don't use pow to square an integer. x * x is clearer, exact and fast. std::pow always works in floating point, so std::pow(n, 2) gives a double you have to convert back.
  • Don't trust pow for exact large integers. A double holds about 15–16 significant digits. std::pow(10, 18) is exactly representable, but many large results are not, and converting them to long long can be off by one.
  • std::sqrt of a negative number is not an error you can catch: it returns NaN ("not a number"). More on that below.

Absolute values, min, max and clamp

std::abs returns the distance from zero. It has overloads for int, long, long long and the floating-point types, so it keeps the type you give it. std::fabs is the floating-point-only version you will see in C-style code.

std::min and std::max come from <algorithm>, and std::clamp(value, low, high) (C++17) keeps a value inside a range, which is perfect for health bars, volume sliders and percentages.

C++ abs, min, max and clamp

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Two pitfalls:

  • std::min(3, 8.5) does not compile: both arguments must have the same type. Write std::min(3.0, 8.5) or std::min<double>(3, 8.5).
  • std::abs of the most negative int is undefined behavior, because its positive twin does not fit in an int. You will see why in Integer Types.

Rounding: round, floor, ceil and trunc

There is no single "correct" way to round, so C++ gives you four:

Function Rule 2.5 -2.5 2.7 -2.7
std::round nearest; halves go away from zero 3 -3 3 -3
std::floor down, toward βˆ’βˆž 2 -3 2 -3
std::ceil up, toward +∞ 3 -2 3 -2
std::trunc toward zero (drop the fraction) 2 -2 2 -2

All four return a floating-point value. If you need an integer, use std::lround / std::llround, which return long / long long, or convert explicitly with static_cast<int>(...). Note that static_cast<int>(-2.7) is -2: converting a floating-point value to an integer always truncates.

C++ Comparing rounding functions

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

To display a number with two decimals, format it with {:.2f} instead of rounding it. Rounding with round(x * 100) / 100 still produces a double, and most decimal fractions (like 19.99) can't be stored exactly in binary. For money, many programs store whole cents in an integer. See Floating-Point Numbers for why.

Exponentials and logarithms

std::exp(x) computes eΛ£, std::log(x) is the natural logarithm (base e), std::log10 is base 10 and std::log2 is base 2. For any other base, divide: log_b(x) = log(x) / log(b).

C++
std::exp(1.0);            // 2.718281828459045
std::log(std::exp(2.0));  // 2
std::log10(1000.0);       // 3
std::log2(1024.0);        // 10
std::log(81.0) / std::log(3.0);  // log base 3 of 81, about 4

std::log2 is handy for questions like "how many times can I halve this?" and "how many bits do I need?" For exact integer answers, though, the bit functions in Bitwise Operators (std::bit_width) avoid floating point entirely.

Trigonometry and std::numbers

The trig functions std::sin, std::cos and std::tan take angles in radians, not degrees. A full turn is 2Ο€ radians, so to convert degrees you multiply by Ο€/180. Since C++20, <numbers> gives you exact-as-possible constants such as std::numbers::pi, so you no longer need M_PI (which was never part of standard C++) or a hand-typed 3.14159.

std::atan2(y, x) returns the angle of the point (x, y) and, unlike atan(y / x), it gets the quadrant right and handles x == 0.

C++ Angles in radians and degrees

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Look closely at cos(90Β°): it prints 0.0000 only because of the formatting. The exact value is a tiny number around 6e-17, because Ο€ itself can't be stored exactly. Never compare trig results with ==.

gcd, lcm and midpoint from <numeric>

<numeric> has three small integer helpers (C++17 and C++20):

  • std::gcd(a, b): the greatest common divisor, the largest number that divides both. Use it to simplify fractions.
  • std::lcm(a, b): the least common multiple, the smallest number both divide. Use it to find when two repeating events line up.
  • std::midpoint(a, b) (C++20): the value halfway between two numbers, computed without overflow. The classic (low + high) / 2 overflows when both are large, a famous bug that hid in binary search code for years.
C++ gcd, lcm and midpoint

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

std::gcd and std::lcm take integers only, and gcd(0, 0) is 0. std::midpoint of two integers rounds toward the first argument when the exact middle isn't a whole number, so midpoint(1, 4) is 2 and midpoint(4, 1) is 3.

Integer division and remainder with negatives

When both operands are integers, / gives an integer result and throws the fraction away. Since C++11 the rule is precise: integer division truncates toward zero. And % is defined so that this always holds:

C++
(a / b) * b + (a % b) == a   // for any b != 0 (and no overflow)

That means the remainder takes the sign of the left operand. Python and some other languages round toward βˆ’βˆž instead, so -7 // 2 is -4 there, but -7 / 2 is -3 in C++.

Expression Result Why
7 / 2 3 3.5 truncated toward zero
-7 / 2 -3 -3.5 truncated toward zero
7 % 3 1 2 Γ— 3 + 1 = 7
-7 % 3 -1 -2 Γ— 3 + (-1) = -7
7 % -3 1 sign follows the left operand

This matters in real code. The test n % 2 == 1 misses negative odd numbers, because -3 % 2 is -1. Write n % 2 != 0 instead. And if you need a remainder that is always in [0, m), for example to wrap an index around a circular buffer, fix the sign yourself:

C++ Division and remainder with negative numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Two more rules:

  • Dividing an integer by zero (with / or %) is undefined behavior. The program may crash, or worse, keep running with garbage. Check the divisor first.
  • The % operator only works on integers. For floating-point values use std::fmod, which follows the same sign rule as %. (std::remainder exists too, but rounds the quotient to the nearest integer, so it can return negative values for positive inputs.)

NaN, infinity and domain errors

Floating-point math doesn't throw exceptions when you ask for something impossible. Instead it returns special values:

  • std::sqrt(-1.0) and std::log(-1.0) return NaN.
  • std::log(0.0) returns βˆ’infinity, and 1.0 / 0.0 gives +infinity (with IEEE 754 doubles, which every mainstream compiler uses).

NaN spreads through every calculation it touches, and it isn't equal to anything, not even itself. Test for it with std::isnan, and for infinities with std::isinf or std::isfinite:

C++
double r = std::sqrt(-4.0);
if (std::isnan(r)) {
    std::println("no real square root");
}

Floating-Point Numbers covers these special values in more depth.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What does std::println("{}", -7 / 2); print?

    Both operands are integers, so the result is an integer, and C++ truncates toward zero. -3.5 becomes -3.
  2. 2. What is the value of -7 % 3 in C++?

    The remainder takes the sign of the left operand so that (a / b) * b + a % b == a. Here (-2) * 3 + (-1) == -7.
  3. 3. Which call returns -3 for the input -2.5?

    floor rounds toward negative infinity, giving -3. ceil and trunc give -2, and converting to int truncates toward zero, also -2. (std::round(-2.5) would give -3 too.)
  4. 4. Why should you prefer std::midpoint(low, high) over (low + high) / 2 for large ints?

    If low and high are both near the maximum int, their sum doesn't fit. std::midpoint computes the middle without forming the overflowing sum.
  5. 5. You need the cosine of 60 degrees. Which expression is right?

    The trig functions take radians. Multiply degrees by pi / 180 to convert. std::cos(60.0) would treat 60 as radians.

Summary

  • <cmath> has the core functions (pow, sqrt, hypot, abs, rounding, trig, exp/log, fmod, isnan); always include it and write std::.
  • Most of them compute in double; integers are converted first. Square integers with x * x, not pow.
  • round (halves away from zero), floor (down), ceil (up) and trunc (toward zero) all return floating-point values; lround returns an integer. Format with {:.2f} to display decimals.
  • Trig functions use radians; std::numbers::pi (C++20) replaces hand-typed constants.
  • <numeric> gives std::gcd, std::lcm and the overflow-safe std::midpoint; <algorithm> gives min, max and clamp.
  • Integer / truncates toward zero, and % takes the sign of the left operand. Integer division by zero is undefined behavior.
  • Impossible floating-point operations return NaN or infinity instead of failing; check with std::isnan and std::isfinite.

Next: Arithmetic Operators, where you'll look closely at + - * / %, type promotion and overflow.