当我尝试求一个数的立方根时会发生奇怪的事情。
以下代码返回未定义。在 cmd 中:-1.#IND
cout<<pow(( double )(20.0*(-3.2) + 30.0),( double )1/3)
虽然这一个工作得很好。在命令中:4.93242414866094
cout<<pow(( double )(20.0*4.5 + 30.0),( double )1/3)
从数学的角度来看,它一定是可行的,因为我们可以从负数中得到立方根。 Pow 来自 Visual C++ 2010 math.h 库。有什么想法吗?
最佳答案
pow(x, y)
来自 <cmath>
如果 x 为负且 y 为非整数,则不起作用。
这是 std::pow
的限制,如 C 标准和 cppreference 中所述:
Error handling
- Errors are reported as specified in math_errhandling
- If base is finite and negative and exp is finite and non-integer, a domain error occurs and a range error may occur.
- If base is zero and exp is zero, a domain error may occur.
- If base is zero and exp is negative, a domain error or a pole error may occur.
有几种方法可以解决此限制:
立方根与取某物的 1/3 次方相同,所以你可以做
std::pow(x, 1/3.)
.在 C++11 中,您可以使用
std::cbrt
. C++11 引入了平方根和立方根函数,但没有通用的 n 次根函数来克服std::pow
的限制。 .
关于c++ - 在 C++ 中找到立方根?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58488910/