Course Content
C++ Data Types
3. Other Data Types and Type Conversion
C++ Data Types
Math in C++
In addition to the +
, -
, *
, /
, and %
operations, we can perform many more mathematical operations using functions from the <cmath>
library.
Here is a table of the most used ones:
Function | Description | Additional info |
cos(x) | Returns the cosinus of x | x is specified in radians |
sin(x) | Returns the sinus of x | x is specified in radians |
tan(x) | Returns the tangens of x | x is specified in radians |
exp(x) | Returns the exponent of x | returns eˣ |
log(x) | Returns the natural logarithm of x | |
pow(x, a) | Returns x to the power of a | |
sqrt(x) | Returns the square root of x | |
cbrt(x) | Returns the cubic root of x | |
ceil(x) | Rounds x up | Example: ceil(5.2) is 6 |
floor(x) | Rounds x down | Example: ceil(5.2) is 5 |
round(x) | Rounds x to nearest | Example: round(5.2) is 5 |
Don't forget to include the library using the following line:
Here is an example of using each of the functions mentioned above:
main.cpp
Note
In the preceding code, we used constants
M_PI
andM_E
for value of π (3.1415...) and e (2.7183..).
They are also defined in the<cmath>
library.
Everything was clear?
Section 1. Chapter 11