Beginner6 min readLesson 12 of 50
The <cmath> Library
C++ provides powerful math functions through the <cmath> header. Include it to access square roots, powers, trigonometry, and more.
#include <iostream>
#include <cmath>
using namespace std;
int main() {
cout << sqrt(25) << endl; // 5
cout << pow(2, 10) << endl; // 1024
cout << abs(-15) << endl; // 15
cout << ceil(4.2) << endl; // 5
cout << floor(4.9) << endl; // 4
cout << round(4.5) << endl; // 5
cout << log(M_E) << endl; // 1 (natural log)
cout << log10(1000) << endl; // 3
return 0;
}
Output:
5
1024
15
5
4
5
1
3
Common Math Functions
| Function | Description | Example |
sqrt(x) | Square root | sqrt(9) → 3 |
pow(x, y) | x to the power y | pow(2,8) → 256 |
abs(x) | Absolute value | abs(-7) → 7 |
ceil(x) | Round up | ceil(3.1) → 4 |
floor(x) | Round down | floor(3.9) → 3 |
round(x) | Round to nearest | round(3.5) → 4 |
sin/cos/tan | Trigonometry (radians) | sin(M_PI/2) → 1 |
max() and min()
These functions are available without any extra header:
cout << max(10, 20); // 20
cout << min(10, 20); // 10
cout << max(3.5, 2.1); // 3.5
Exercise
Write a program that reads a number from the user and prints its square root, square (power of 2), and absolute value.
Show Solution
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double n;
cout << "Enter a number: "; cin >> n;
cout << "Square root: " << sqrt(n) << endl;
cout << "Squared: " << pow(n, 2) << endl;
cout << "Absolute: " << abs(n) << endl;
return 0;
}
Quiz
Which header provides sqrt() and pow()?
- A)
<math> - B)
<cmath> - C>
<algorithm> - D)
<numbers>
Answer
B) <cmath>
What does ceil(4.1) return?
Answer
C) 5 — ceil always rounds up to the next whole number.
Summary
- Include
<cmath> for math functions.
- Key functions:
sqrt, pow, abs, ceil, floor, round.
max() and min() work without extra headers.