Math
Lesson 9Author : Afrixi
Last Updated : November, 2022
Table of Content
Math
C++ provides a variety of mathematical functions and operators that can be used to perform calculations. Here are some examples:
Basic arithmetic operators
C++ supports the basic arithmetic operators +
(addition), -
(subtraction), *
(multiplication), and /
(division). For example:
int x = 5;
int y = 3;
int sum = x + y;
int product = x * y;
int quotient = x / y;
In this code, the variables x
and y
are used with the arithmetic operators to perform addition, multiplication, and division, and the results are stored in the variables sum
, product
, and quotient
.
The modulus operator
The modulus operator %
returns the remainder of a division operation. For example:
int x = 5;
int y = 3;
int remainder = x % y;
In this code, the modulus operator is used to calculate the remainder when x
is divided by y
, and the result is stored in the variable remainder
.
Math functions
C++ provides a variety of built-in math functions, including sqrt()
(square root), pow()
(raise to a power), abs()
(absolute value), sin()
(sine), cos()
(cosine), tan()
(tangent), and many others. For example:
#include <cmath>
double x = 2.0;
double y = sqrt(x);
double z = pow(x, 3);
In this code, the sqrt()
and pow()
functions from the cmath
library are used to calculate the square root of x
and raise x
to the power of 3, respectively, and the results are stored in the variables y
and z
.
Increment and decrement operators
C++ provides the increment operator ++ and decrement operator –, which can be used to add or subtract 1 from a variable, respectively. For example:
int x = 5;
x++;
int y = 3;
y--;
In this code, the variables x
and y
are incremented and decremented, respectively.
These are just a few examples of the mathematical functions and operators available in C++. There are many more that can be used to perform complex calculations and manipulate data.