course content

Course Content

C++ Data Types

Math in C++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:

FunctionDescriptionAdditional info
cos(x)Returns the cosinus of xx is specified in radians
sin(x)Returns the sinus of xx is specified in radians
tan(x)Returns the tangens of xx is specified in radians
exp(x)Returns the exponent of xreturns 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 upExample: ceil(5.2) is 6
floor(x)Rounds x downExample: ceil(5.2) is 5
round(x)Rounds x to nearestExample: 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:

cpp

main.cpp

Note

In the preceding code, we used constants M_PI and M_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