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 assqrt,pow,round,abs,ceil, andfloor, - explain why
7 / 2gives3, not3.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.
| Function | What it does | Example | Result |
|---|---|---|---|
sqrt(x) | square root | sqrt(9.0) | 3.0 |
pow(x, y) | x raised to the power y | pow(2.0, 3.0) | 8.0 |
abs(x) | absolute value (drops the minus sign) | abs(-4) | 4 |
round(x) | rounds to the nearest whole number | round(2.7) | 3.0 |
ceil(x) | rounds UP to a whole number | ceil(2.1) | 3.0 |
floor(x) | rounds DOWN to a whole number | floor(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.