C++ Math
The `<cmath>` header provides mathematical functions like `sqrt()`, `pow()`, `abs()`, `floor()` and `ceil()`. These work with doubles and floats for precise calculations.
For generating random numbers, modern C++ prefers `<random>` over the old `rand()` function, since it produces better-quality randomness.
Common functions
`sqrt(x)` returns the square root, `pow(x, y)` raises x to the power y, `abs(x)` returns the absolute value, and `max(a, b)`/`min(a, b)` from `<algorithm>` compare two values.
Rounding
`floor(x)` rounds down, `ceil(x)` rounds up, and `round(x)` rounds to the nearest integer โ all return a double.
#include <cmath>
#include <iostream>
int main() {
std::cout << sqrt(16) << " " << pow(2, 3);
}4 8sqrt(16) is 4; pow(2,3) is 2 cubed = 8.
#include <algorithm>
std::cout << std::max(3, 7);7std::max returns the larger of two values.
Key points
- <cmath> provides sqrt, pow, abs, floor, ceil.
- <algorithm> provides std::max and std::min.
- Prefer <random> over rand() for quality randomness.
- Math functions typically operate on and return doubles.
