C++ Math (cmath)
C++ has two places for mathematics: std::max and std::min in the algorithm header, and the functions of the cmath header (square roots, powers, rounding and trigonometry).
max and min
#include <algorithm>
#include <iostream>
int main() {
std::cout << std::max(7, 12) << "\n";
std::cout << std::min(7, 12) << "\n";
std::cout << std::max({4, 19, 8, 11}) << "\n"; // several values in braces
return 0;
}12 7 19
Both values must have the same type: std::max(3, 4.5) does not compile; write std::max(3.0, 4.5).
cmath
| Function | Result |
|---|---|
std::sqrt(x) | square root |
std::pow(x, y) | x to the power y |
std::abs(x) | absolute value (whole numbers and decimals) |
std::round(x), std::floor(x), std::ceil(x) | nearest, down, up |
std::sin(x), std::cos(x), std::tan(x) | trigonometry, x in radians |
std::log(x), std::log10(x), std::exp(x) | logarithms and e to the x |
std::hypot(x, y) | the length of the hypotenuse |
#include <cmath>
#include <cstdlib>
#include <iostream>
int main() {
std::cout << std::sqrt(64) << "\n";
std::cout << std::pow(2, 10) << "\n";
std::cout << std::abs(-4.5) << "\n";
std::cout << std::round(4.5) << " " << std::floor(4.8) << " " << std::ceil(4.2) << "\n";
std::cout << std::hypot(3, 4) << "\n";
return 0;
}8 1024 4.5 5 4 5 5
Angles in radians
The trigonometric functions use radians. C++20 gives the exact value of pi as std::numbers::pi in the numbers header:
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <numbers>
int main() {
double degrees = 30;
double radians = degrees * std::numbers::pi / 180;
std::cout << std::fixed << std::setprecision(2);
std::cout << "sin(30) = " << std::sin(radians) << "\n";
std::cout << "cos(60) = " << std::cos(60 * std::numbers::pi / 180) << "\n";
return 0;
}sin(30) = 0.50 cos(60) = 0.50
Decimals are approximate
A double stores most decimal fractions approximately: 0.1 + 0.2 is very slightly more than 0.3. Never test decimals with ==; check that the difference is tiny: std::abs(a - b) < 1e-9.
#include <cmath>
#include <cstdlib>
#include <iostream>
int main() {
double a = 0.1 + 0.2;
std::cout << std::boolalpha;
std::cout << (a == 0.3) << "\n";
std::cout << (std::abs(a - 0.3) < 1e-9) << "\n";
return 0;
}false true
Integer and decimal versions
std::abs works for both whole numbers and decimals: the integer versions are declared in cstdlib, the decimal ones in cmath, which is why the examples include both. The functions of cmath return double, so std::pow(2, 10) is the decimal 1024.0; for an exact integer power of small numbers, a loop or a bit shift (1 << 10) is better. Store the result of std::round in an int with static_cast<int>(std::round(x)).
Practice exercises
- Compute the area of a circle with radius 5 using
std::numbers::pi. - Read a number and print its square root, or a message if it is negative.
- Compute 1000 at 7% interest for 10 years: 1000 × 1.07 to the power 10.