Math Functions
C++ has operators for +, -, *, / and %, but there is no operator for a power or a square root. For these, C++ has ready-made math functions in the <cmath> library. Add #include <cmath> at the top of the program to use them.
To use a function, write its name and put the values in parentheses, like sqrt(25). This is called calling the function. The call gives back a result, which you can print or store. You will write your own functions later, in the Functions section.
#include <iostream>
#include <cmath>
using namespace std;
int main() {
cout << sqrt(25) << "\n";
cout << sqrt(2) << "\n";
cout << pow(2, 10) << "\n";
return 0;
}
Output:
5
1.41421
1024
sqrt(x) gives the square root of x. pow(x, y) gives x to the power y, so pow(2, 10) is ten 2s multiplied together, which is 1024.
Do not write 2 ^ 10 for a power. In C++, ^ is a different operator that works on the bits of a number, so it gives a strange answer and no error:
cout << (2 ^ 10) << "\n";
Output:
8
pow gives back a double
pow gives back a double, even when both values are whole numbers. Remember from the Data Types lesson that cout shows a double with at most 6 significant digits:
cout << pow(10, 6) << "\n";
int million = pow(10, 6);
cout << million << "\n";
Output:
1e+06
1000000
The first line printed 1e+06, the short form for 1,000,000. To print all the digits, store the result in an int first. As you saw in the last lesson, putting a double into an int drops the decimal part. Here there is no decimal part to lose, so million is exactly 1000000.
abs
abs(x) gives the absolute value of x: the same number without its minus sign. Use it when you need the distance between two numbers and do not care which one is bigger:
int a = 3;
int b = 10;
cout << abs(a - b) << "\n";
cout << abs(-2.5) << "\n";
Output:
7
2.5
round, floor and ceil
These three turn a decimal number into a whole number, each in its own way:
| Function | What it does | Example |
|---|---|---|
round(x) | goes to the nearest whole number | round(2.4) is 2 |
floor(x) | always goes down | floor(2.7) is 2 |
ceil(x) | always goes up | ceil(2.1) is 3 |
cout << round(2.4) << " " << round(2.5) << "\n";
cout << floor(2.7) << " " << ceil(2.1) << "\n";
Output:
2 3
2 3
round(2.5) gives 3. When a number is exactly in the middle, round goes away from zero, so 2.5 becomes 3 and -2.5 becomes -3.
ceil is useful when you must count something that cannot be split. If 23 people ride in cars that hold 5 people each, you need 23 / 5 = 4.6 cars, so 5 cars:
int people = 23;
int seats = 5;
cout << ceil(people / 5.0) << "\n";
cout << ceil(people / seats) << "\n";
Output:
5
4
The second line is wrong. people / seats is an int division, so it was already 4 before ceil saw it. This is the same mistake as in the last lesson: make the division a double division first.
In the exercise, use pow, sqrt and round on two numbers that you read.