c++ - 在 C++ 中找到立方根?

标签 c++ math.h pow

当我尝试求一个数的立方根时会发生奇怪的事情。

以下代码返回未定义。在 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/4269069/

相关文章:

c++ - 数据模型问题

c++ - LoadLibraryW 在 LoadLibraryA 完成工作时不起作用

c++ - Linux Posix 队列打开的文件太多

c - 使用标准 C 数学库实现 sinpi() 和 cospi()

c - 理解 C 头文件语法

c++ - math.h pow() 函数无法正常工作?

c - 对变量和常量的操作在c中给出不同的结果

c++ - 为什么我的 HelloWorld 函数没有在这个范围内声明?

c - Raspberry PI 中的幂函数

c - 如果分配给整数,则 pow() 的返回值会向下舍入