Stage 8: Basic Math Functions from the <cmath> Library
A detailed summary of the most important mathematical operations in C++ - an essential for every programming exam.
The <cmath> Library: Calculation Foundations
During exams, you'll often face tasks requiring distance calculations, powers, or rounding. Instead of writing custom functions, use the <cmath> library, which is optimized and precise.
1. Basic Operations: Powers and Roots
The most important functions are pow and sqrt. Note: both functions take and return the double type.
pow(a, b): Calculates (a to the power of b).sqrt(x): Calculates (square root).
#include <iostream>
#include <cmath>
int main() {
double base = 5.0;
double exp = 2.0;
std::cout << "Result: " << pow(base, exp) << std::endl; // 25.0
return 0;
}2. Rounding and Absolute Value
C++ provides several ways to control fractional parts depending on your needs.
ceil(x): Rounds up (e.g., 3.1 -> 4.0).floor(x): Rounds down (e.g., 3.9 -> 3.0).round(x): Mathematical rounding (up from .5).fabs(x): Returns the absolute value of a floating-point number.
3. Trigonometry (Radians vs Degrees)
The most common trap! Functions like sin(), cos(), and tan() expect arguments in radians.
Conversion formula:
const double PI = 3.1415926535;
double rad = 30.0 * (PI / 180.0);
double s = sin(rad); // approx 0.5Exam Tips
- Always use
.0: When writingpow(2, 2), you risk ambiguity. Usepow(2.0, 2.0)instead. - Error Handling: Remember that
sqrtof a negative number won't trigger a compiler error, but your program will returnNaN(Not a Number). - PI Constant: If
M_PIis not defined, useacos(-1.0)to get a highly accurate value of Pi.
You might also like
Stage 7: Basic Algorithms in C++ - Manual Implementation
A guide to copying, searching, sorting, and sequence generation algorithms without using the <algorithm> library.
Stage 5: References and References as Function Parameters
Understanding the reference mechanism in C++: how variable aliases work and why they are key to efficient argument passing.
Stage 1: Basic Data Types in C++ - A Comprehensive Guide
A detailed discussion of data types in C++, considering memory sizes and common exam mistakes.