In C++ simple arithmetic can be performed with the basic arithmetic operators, but these operators are limited in the scope of mathematical function they perform. C++ has many other mathematical functions included in the
To use any of the operations discussed in this post the <cmath>
library must be included with a preprocessor directive:
#include <cmath>
An exponent in the form is written in C++:
pow(x, y)
Which will return a double
result which can be used in an expression. For example, to write the expression :
double result = pow(4, 1 / 2); // result is 2
The pow()
operation can be combined to make more complex mathematical expressions, such as the equation for the area of a circle:
Which can be written in C++:
double pi = 3.14, r = 7.25; double area = pi * pow(r, 2); // area is 165.04625
A square root in the form is written in C++:
sqrt(x)
Which will return a double
result which can be used in an expression. For example, to write the expression :
double result = sqrt(25); // result is 2
Like before, sqrt()
can also be used in more complex equations. Such as in the equation of a getting the radius of a circle from the area:
Which can be written in C++:
double pi = 3.14, A = 165.04625; double radius = sqrt(A / pi); // radius is 7.25
An absolute value in the form is written in C++:
abs(x)
Which will return a double
result which can be used in an expression. For example, to write the expression :
double result = abs(-67.234); // result is 2
As with the previous operations, abs()
can also be used in more complex equations. Such as in the equation of finding the distance between two x points:
Which can be written in C++:
double x1 = 10, x2 = 97.25; double distance = abs(x1 - x2); // radius is 7.25
Numbers can be rounded in three ways:
Operation | Symbol | Command |
---|---|---|
Round to Nearest | ~x | round(x) |
Round Down | ⌊x⌋ | floor(x) |
Round Up | ⌈x⌉ | ceil(x) |
Round to nearest works as expected from math, decimal values with .5 or higher are rounded up, otherwise they are rounded down. Round down will always round down regardless of decimal value, and round up will always round up regardless of decimal value.
For example, to show the 3 different rounding types on the distance calculated above:
double x1 = 10, x2 = 97.25; double distance = abs(x1 - x2); // radius is 7.25 double r = round(distance); // r is 7 double f = floor(distance); // f is 7 double c = ceil(distance); // c is 8
There are 3 basic trigonometric functions (see here for more complex trigonometric functions):
Operation | Command |
---|---|
Sine | sin(x) |
Cosine | cos(x) |
Tangent | tan(x) |
The trigonometric functions operate on angles in radians from the unit circle:
From the unit circle it can be seen that each angle in degrees correlates to some . These values are the radian equivalents to the angles in degrees. However, when typically working with angles they are in degrees rather than radians. Thus whenever working with angles in degrees they must first be converted to radians prior to passing the values to the trigonometric functions. The equation to convert a value from degrees to radians is:
Thus to take the sin
cos
and tan
of an angle 60
in degrees:
const double pi = 3.14; double degrees = 60; double radians = degrees * pi / 180; double s = sin(radians); // s is 0.8660254 double c = cos(radians); // c is 0.5 double t = tan(radians); // t is 1.73205081
As per the other commands, the trigonometric functions can be combined with arithmetic to form complex expressions. For example, if an observer is standing on the ground some feet away from an object and they calculate the angle from the ground where they stand to the top of the object, they can calculate the height of the object with:
Where distance
is how many feet the observer is from the object and angle
is the angle from the ground where the observer is to the top of the object. So to use C++ to calculate the height of an object 30 feet away at an angle of 60° to the top of the object:
const double pi = 3.14; double distance = 30, degrees = 60; double radians = degrees * pi / 180; // Use tangent to find the height double height = distance * tan(radians);
The distance from the ground where the observer is standing to the top of the object (called the hypotenuse) can also be calculated by changing the tan
in the equation to cos
:
Which can be added to the above code snippet:
const double pi = 3.14; double distance = 30, degrees = 60; double radians = degrees * pi / 180; // Use tangent to find the height double height = distance * tan(radians); // Use cosine to find the hypotenuse (line of sight) double hypotenuse = distance / cos(radians);
Lastly, once the hypotenuse is calculated it can be used to calculate the height of the object (so the two calculations can be verified). To use the hypotenuse to calculate the height of the object use:
Which can be added to the above code snippet:
const double pi = 3.14; double distance = 30, degrees = 60; double radians = degrees * pi / 180; // Use tangent to find the height double height = distance * tan(radians); // Use cosine to find the hypotenuse (line of sight) double hypotenuse = distance / cos(radians); // Use sin to verify height double height_check = hypotenuse * sin(radians);
In a video game where you fight monsters your player might be able to attack from far away using range or magic, but not from too far away. To calculate how far the player is from the monster the euclidean distance formula is used:
Write a program that reads in the x and y coordinates of a player, calculates the distance to a monster at coordinates (10, 3), rounds the distance calculated up, then outputs the distance.
First, the x and y coordinates of the player need to be read in:
#include <iostream> using namespace std; int main() { int player_x = 0, player_y = 0; // Get x-coordinate cout << "X-Coordinate: "; cin >> player_x; // Get y-coordinate cout << "Y-Coordinate: "; cin >> player_y; return 0; }
The distance from the entered coordinates to the monster can then be computed using the euclidean distance formula:
#include <iostream> #include <cmath> using namespace std; int main() { int player_x = 0, player_y = 0, monster_x = 10, monster_y = 3; // Get x-coordinate cout << "X-Coordinate: "; cin >> player_x; // Get y-coordinate cout << "Y-Coordinate: "; cin >> player_y; // Calculate distance double distance = pow(player_x - monster_x, 2); // x-distance distance += pow(player_y - monster_y, 2); // y-distance distance = sqrt(distance); // square added distances return 0; }
The <cmath>
library is first included so the mathematical functions pow()
and sqrt()
can be used in the euclidean distance formula. The coordinates are then applied to the euclidean distance formula by first computing the distance between the x-coordinates. Then the distance between the y-coordinates is calculated and added to the distance between the x-coordinates. Finally, the square root of the sum of two distances is taken. The value can then be rounded and output:
#include <iostream> #include <cmath> using namespace std; int main() { int player_x = 0, player_y = 0, monster_x = 10, monster_y = 3; // Get x-coordinate cout << "X-Coordinate: "; cin >> player_x; // Get y-coordinate cout << "Y-Coordinate: "; cin >> player_y; // Calculate distance double distance = pow(player_x - monster_x, 2); // x-distance distance += pow(player_y - monster_y, 2); // y-distance distance = sqrt(distance); // square added distances // Round distance up distance = ceil(distance); //Output results cout << "(" << player_x << ", " << player_y << ") is " << distance << " tiles from " << "(" << monster_x << ", " << monster_y << ")\n"; return 0; }
The ceil()
function is used to always round the value of distance
up. Both the player and monster's coordinates and the distance are then output.
So if the value 1
was entered for the player_x
and the value 17
was entered for the player_y
, then the following would be output:
X-Coordinate: 1 Y-Coordinate: 17 (1, 17) is 17 tiles from (10, 3)
See operations above
What is sqrt(25)
?
What is pow(2, 3)
?
What is abs(-10)
?
What is round(2.6)
?
What is ceil(4.2)
?
What is floor(4.9)
?
What is sin(0)
?
What is cos(0)
?
What is tan(0)
?
What is sin(3.14 / 2)
?
What is cos(3.14)
?
What is tan(3.14 / 4)
?
What is pow(2, 3) + sqrt(49)
?
Evaluate abs(-12) + ceil(2.3)
.
Compute floor(5.8) * round(3.6)
.
What is pow(3, 2) - abs(-4)
?
What is sqrt(100) / 5
?
Evaluate sin(3.14 / 2) * 10
.
Compute cos(0) + tan(3.14 / 4)
.
What is ceil(2.1) + floor(3.9)
?
What is round(sqrt(50))
?
What is abs(-5) + pow(2, 3) - sqrt(36)
?
What is round(2.4) * ceil(3.1) + floor(7.9)
?
Evaluate abs(-10) + sqrt(49) * 2 - pow(3, 2)
.
Compute round(pow(2, 1.5)) + floor(9.99)
What is sin(3.14 / 2) + cos(0) + tan(3.14 / 4)
?
Evaluate (sqrt(16) + pow(2, 2)) / abs(-4)
Compute ceil(sqrt(30)) * round(2.5)
Evaluate round(sin(3.14 / 2) * 10) - abs(-3)
static_cast
What is static_cast<int>(sqrt(10))
?
Compute static_cast<double>(abs(-8)) / 3
.
What is static_cast<int>(round(3.6)) * 2
?
What does static_cast<int>(tan(3.14 / 4) + 0.9)
yield?
What is pow(static_cast<double>(2), 4)
?
Compute static_cast<int>(ceil(5.1)) + static_cast<int>(floor(5.9))
What is static_cast<int>(sqrt(90)) + static_cast<int>(floor(8.6))
?
What does static_cast<int>(pow(2.0, 3.0) + abs(-5))
return?
Compute static_cast<double>(round(3.6) + 2) / 3
Evaluate static_cast<int>(round(sqrt(50))) * 2
What is static_cast<int>(ceil(tan(3.14 / 4) + 0.9))
?
Evaluate abs(static_cast<int>(floor(9.9) - ceil(3.1)))
What is static_cast<int>(abs(-5) + round(2.7) + floor(3.9))
?
stoi
, stod
, to_string
What is sqrt(stoi("49"))
?
Evaluate pow(stod("2.0"), stod("3.0"))
.
What is abs(stoi("-5")) * 2
?
What is round(stod("4.7")) + 1
?
What does to_string(ceil(stod("4.1")))
return?
Evaluate stod("3.14") * sin(stod("1.57"))
What is floor(stod("9.99")) - stoi("4")
?
What is pow(stoi("3"), 3)
?
What does sqrt(stod("64.0"))
evaluate to?
Evaluate abs(stoi("-100")) / 5
Compute round(stod("6.66")) + stoi("1")
What is to_string(pow(2, 4))
?
What does stod("3.14") * sin(stod("1.57"))
yield?
What is stoi("16") - static_cast<int>(sqrt(16))
?
Evaluate to_string(static_cast<int>(sqrt(stod("36.0")) + stoi("4")))
What is pow(static_cast<double>(stoi("2")), stoi("3"))
?
Evaluate static_cast<int>(round(sqrt(stod("81.0")) + pow(2, 2)))
What does to_string(abs(static_cast<int>(stod("9.1") - 10)))
return?
Compute static_cast<double>(stoi("5") + static_cast<int>(floor(stod("4.9")))) / 2
Evaluate round(sqrt(pow(stoi("3"), 2) + pow(stoi("4"), 2)))
What is to_string(static_cast<int>(pow(stod("2.5"), 2) + abs(stoi("-6"))))
?
Compute sin(stod("1.57")) * pow(static_cast<double>(stoi("2")), 2)
Evaluate to_string(static_cast<int>(sqrt(pow(stoi("3"), 2) + pow(stoi("4"), 2))))
.
Ask the user for a number and print its square root.
Ask for a base and an exponent, then print the result of .
Prompt the user for a negative number and print its absolute value.
Ask the user for a decimal number and print its rounded value.
Input a number as a string, convert it to double using stod
, and take the square root.
Ask for a decimal number and print the ceil
, floor
, and round
values.
Ask for the time in seconds and print the fall distance using:
Ask for the radius of a circular fountain and calculate the area using the equation:
Ask for the radius and height of a soda can and compute the volume using the equation:
Ask for the width and height of a computer screen in inches and compute the diagonal using the Pythagorean theorem:
Ask the user for the coefficients a, b, and c of a quadratic equation and compute the roots using the quadratic formula:
Ask for (x₁, y₁) and (x₂, y₂) coordinates of two points and compute the euclidean distance using:
Ask for (x₁, y₁) and (x₂, y₂) coordinates of two points and compute the manhattan distance using:
Ask for the floor length and width of a room and tile size, then calculate how many tiles are needed:
Ask for wall dimensions and coverage per gallon of paint and calculate the gallons required:
Ask for the rise and run of a wheelchair ramp and calculate the angle in degrees:
Ask for number of steps and step height, compute total staircase height:
Ask for ceiling height and fan drop distance and compute the clearance:
Ask for the height of a cliff and calculate time to hit the water using:
Ask for the height of an object and the angle of the sun in degrees, calculate the shadow length:
Ask for the final speed and acceleration, calculate time to reach that speed:
Ask for the tire volume and pressure loss per day, estimate days until empty: