The C++ Standard Library provides a set of functions in the <cmath>
header that operate on double
values. Here are some commonly used functions:
std::abs(double x)
: Returns the absolute value of x
.
#include <cmath>
double absValue = std::abs(-5.6); // Returns 5.6
std::sqrt(double x)
: Returns the square root of x
. If x
is negative, it results in NaN (Not-a-Number).
double squareRoot = std::sqrt(25.0); // Returns 5.0
std::pow(double base, double exponent)
: Returns base
raised to the power of exponent
.
double result = std::pow(2.0, 3.0); // Returns 8.0
std::exp(double x)
: Returns e
raised to the power of x
, where e
is the base of natural logarithms.
double expValue = std::exp(1.0); // Returns approximately 2.71828
std::log(double x)
: Returns the natural logarithm (base e
) of x
.
double logValue = std::log(2.71828); // Returns 1.0
std::log10(double x)
: Returns the base-10 logarithm of x
.
double log10Value = std::log10(100.0); // Returns 2.0
std::sin(double x)
: Returns the sine of x
(where x
is in radians).
double sineValue = std::sin(3.14 / 2); // Returns approximately 1.0
std::cos(double x)
: Returns the cosine of x
(where x
is in radians).
double cosineValue = std::cos(0.0); // Returns 1.0
std::tan(double x)
: Returns the tangent of x
(where x
is in radians).
double tangentValue = std::tan(0.0); // Returns 0.0
std::ceil(double x)
: Returns the smallest integer value not less than x
.
double ceilValue = std::ceil(4.3); // Returns 5.0
std::floor(double x)
: Returns the largest integer value not greater than x
.
double floorValue = std::floor(4.7); // Returns 4.0
std::fmod(double x, double y)
: Returns the remainder of x
divided by y
.
double remainder = std::fmod(7.0, 3.0); // Returns 1.0
std::round(double x)
: Rounds x
to the nearest integer.
double roundedValue = std::round(4.5); // Returns 5.0
std::trunc(double x)
: Truncates x
to the nearest integer towards zero.
double truncatedValue = std::trunc(4.9); // Returns 4.0
std::hypot(double x, double y)
: Returns the square root of x^2 + y^2
, useful for computing the length of the hypotenuse in a right triangle.
double hypotenuse = std::hypot(3.0, 4.0); // Returns 5.0
Here’s a simple example illustrating some of these functions:
#include <iostream>
#include <cmath>
int main() {
double a = -3.7;
double b = 4.2;
std::cout << "Absolute value of a: " << std::abs(a) << std::endl;
std::cout << "Square root of b: " << std::sqrt(b) << std::endl;
std::cout << "a raised to the power of b: " << std::pow(a, b) << std::endl;
std::cout << "Natural log of b: " << std::log(b) << std::endl;
std::cout << "Sine of 45 degrees: " << std::sin(45.0 * M_PI / 180.0) << std::endl;
return 0;
}
This code snippet demonstrates the use of std::abs
, std::sqrt
, std::pow
, std::log
, and std::sin
functions with double
values.