C++ provides a variety of mathematical functions that you can use to perform mathematical operations on numbers. These functions are available in the <cmath> header file.
Some of the most common mathematical functions in C++ include:
Examples
The following code shows how to use some of the most common mathematical functions in C++:
#include <iostream>
#include <cmath>
int main() {
// Raise a number to a power.
double result = pow(2, 3);
// Calculate the square root of a number.
result = sqrt(16);
// Calculate the sine of an angle.
result = sin(45 * M_PI / 180);
// Calculate the cosine of an angle.
result = cos(45 * M_PI / 180);
// Calculate the tangent of an angle.
result = tan(45 * M_PI / 180);
// Calculate the natural logarithm of a number.
result = log(10);
// Calculate the exponential of a number.
result = exp(1);
// Print the results to the console.
std::cout << result << std::endl;
return 0;
}
Output:
8
4
0.707107
0.707107
1
2.30259
You can also use the mathematical functions in C++ to perform more complex mathematical operations, such as calculating the area of a triangle or the volume of a sphere.
For example, the following code calculates the area of a triangle:
#include <iostream>
#include <cmath>
int main() {
// Declare the variables.
double base = 10;
double height = 5;
// Calculate the area of the triangle.
double area = 0.5 * base * height;
// Print the result to the console.
std::cout << area << std::endl;
return 0;
}
Output:
25
The mathematical functions in C++ are a powerful tool that you can use to perform a wide variety of mathematical operations. I hope this explanation is helpful. Please let me know if you have any other questions.