如何获得C ++中的多维数据集根? [英] How can I obtain the cube root in C++?
问题描述
我知道如何使用 sqrt
函数获取数字的平方根。
I know how to obtain the square root of a number using the sqrt
function.
如何获取数字的立方根?
推荐答案
sqrt
表示平方根,平方根表示提高到 1/2
的大小。没有诸如具有根2的平方根或具有根3的平方根这样的东西。对于其他根,您可以更改第一个字词; 在您的情况下,您正在寻求如何执行多维数据集生成 。
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.
在C ++ 11之前,没有具体的功能,但你可以回到第一个原则:
Before C++11, there is no specific function for this, but you can go back to first principles:
- 平方根:
std :: pow (n,1/2。)
(或std :: sqrt(n)
) - 立方根:
std :: pow(n,1/3)
(或std :: cbrt(n)
,因为C ++ 11) - 第四根:
std :: pow(n,1/4。)
- 等。
- 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.
如果你期望为 n
传递负值,请避免 std :: pow
solution— 它不支持具有小数指数的负输入,这就是为什么 std :: cbrt
已添加:
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
。真的很重要,因为否则
1/3
使用整数除法,结果 0
。
N.B. That .
is really important, because otherwise 1/3
uses integer division and results in 0
.
这篇关于如何获得C ++中的多维数据集根?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!