Skip to content

Doing Math in C++: The cmath Library and Number Pitfalls

Programming C++ Difficulty 1/5

Beginning of the lesson

Doing Math in C++: The cmath Library and Number Pitfalls

Get the right answer, not a silent wrong one

Big Idea: C++ loves math, but numbers follow strict rules. The <cmath> library hands you ready-made tools like sqrt and pow. At the same time, a few traps — such as whole-number division and tiny rounding errors — can make your program quietly print the wrong answer. This lesson shows you both the tools and the traps so your math is always correct.
By the end you will be able to:
  • use <cmath> functions such as sqrt, pow, round, abs, ceil, and floor,
  • explain why 7 / 2 gives 3, not 3.5,
  • use the modulo operator % correctly,
  • spot floating-point rounding error and integer overflow,
  • pick the right numeric type so your answers stay correct.

1. The <cmath> toolbox

You already know operators like +, -, * and / from the Operators and Expressions lesson. But how do you find a square root, or raise a number to a power? C++ keeps those in a toolbox called <cmath>. You open the toolbox by adding one line at the top of your file:

#include <cmath>

Once it is included, you can call these handy functions. Think of each one as a little machine: you feed it a number, it hands one back.

FunctionWhat it doesExampleResult
sqrt(x)square rootsqrt(9.0)3.0
pow(x, y)x raised to the power ypow(2.0, 3.0)8.0
abs(x)absolute value (drops the minus sign)abs(-4)4
round(x)rounds to the nearest whole numberround(2.7)3.0
ceil(x)rounds UP to a whole numberceil(2.1)3.0
floor(x)rounds DOWN to a whole numberfloor(2.9)2.0

Here they are working together in a real program:

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    cout << sqrt(16.0) << endl;   // 4
    cout << pow(3.0, 2.0) << endl; // 9
    cout << abs(-7) << endl;       // 7
    cout << round(4.6) << endl;    // 5
    return 0;
}
Most <cmath> functions work on double (decimal) numbers and give back a double. That is why we wrote 16.0 and not just 16.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers