How can I obtain the cube root in C++?

后端 未结 8 1997
你的背包
你的背包 2020-12-09 02:12

I know how to obtain the square root of a number using the sqrt function.

How can I obtain the cube root of a number?

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 02:53

    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.) (or std::sqrt(n))
    • Cube root: std::pow(n, 1/3.) (or std::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.

提交回复
热议问题