How can I obtain the cube root in C++?
in C++11 std::cbrt
was introduced as part of math library, you may refer
include <cmath>
std::pow(n, 1./3.)
Also, in C++11 there is cbrt
in the same header.
Math for Dummies.
sqrt
stands for "square root", and "square root" means raising to the power of 1/2
. There is no such thing as "square root with root 2", or "square root with root 3". For other roots, you change the first word; in your case, you are seeking how to perform cube rooting.
Before C++11, there is no specific function for this, but you can go back to first principles:
- Square root:
std::pow(n, 1/2.)
(orstd::sqrt(n)
) - Cube root:
std::pow(n, 1/3.)
(orstd::cbrt(n)
since C++11) - Fourth root:
std::pow(n, 1/4.)
- etc.
If you're expecting to pass negative values for n
, avoid the std::pow
solution — it doesn't support negative inputs with fractional exponents, and this is why std::cbrt
was added:
std::cout << std::pow(-8, 1/3.) << '\n'; // Output: -nan
std::cout << std::cbrt(-8) << '\n'; // Output: -2
N.B. That .
is really important, because otherwise 1/3
uses integer division and results in 0
.