C++ - Math
Overview
Estimated time: 25–35 minutes
Use <cmath>
for common math functions and <limits>
for numeric traits.
Learning Objectives
- Call cmath functions correctly (overloads for float/double/long double).
- Use std::numeric_limits to query type properties.
Prerequisites
Common math
#include <cmath>
#include <iostream>
int main(){
std::cout << std::sqrt(9.0) << "\n"; // 3
std::cout << std::pow(2.0, 3.0) << "\n"; // 8
}
numeric_limits
#include <limits>
#include <iostream>
int main(){
std::cout << std::numeric_limits<int>::max() << "\n";
}
Common Pitfalls
- Using integers with cmath functions may select unintended overloads; cast to double when needed.
Exercises
- Compute hypotenuse length with sqrt(a*a+b*b).