The <cmath> Library in C++ – Math Essentials
An overview of essential math functions in C++: from powers and roots to advanced trigonometry.
Introduction to <cmath>
The <cmath> library (inherited from C as math.h) provides a set of functions for mathematical operations on floating-point numbers. All functions reside in the std namespace.
Basic Operations
The most commonly used functions include:
std::pow(base, exp)– Calculates power .std::sqrt(x)– Square root .std::abs(x)– Absolute value .
Rounding Functions
Choosing the right rounding function is crucial for calculation precision:
std::ceil(x): Rounds up (ceiling).std::floor(x): Rounds down (floor).std::round(x): Rounds to the nearest integer.std::trunc(x): Truncates the fractional part (rounds towards zero).
Trigonometry
Remember that trigonometric functions in C++ expect arguments in radians, not degrees:
#include <iostream>
#include <cmath>
int main() {
double degrees = 90.0;
double radians = degrees * (M_PI / 180.0);
std::cout << "Sin of 90 degrees: " << std::sin(radians) << std::endl;
return 0;
}Note: The
M_PIconstant is not strictly part of the C++ standard, though many compilers provide it. In modern C++ (C++20 and later), it's better to usestd::numbers::pifrom the<numbers>header.
You might also like
Understanding the #include Directive in C++
A guide to the #include directive: learn how the preprocessor links files and why the choice of brackets matters.
C-Style Strings: Char Arrays and Null Termination
Understanding low-level text handling: how character arrays terminated by a null byte work.
Basic C++ Algorithms: Sorting, Searching, and Generating
Harness the power of the <algorithm> library. A guide to std::sort, std::find, std::copy, and sequence generation.