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

后端 未结 8 1939
你的背包
你的背包 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:47
    include <cmath>
    std::pow(n, 1./3.)
    

    Also, in C++11 there is cbrt in the same header.

    Math for Dummies.

    0 讨论(0)
  • 2020-12-09 02:50

    The nth root of x is equal to x^(1/n), so use std::pow. But I don't see what this has to with operator overloading.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-09 02:55

    in C++11 std::cbrt was introduced as part of math library, you may refer

    0 讨论(0)
  • 2020-12-09 02:59
    1. sqrt() is not an operator.
    2. You cannot overload sqrt().

    Please explain why do you need to overload sqrt() so we can help you to do what you want.

    0 讨论(0)
  • 2020-12-09 02:59

    I would discourage any of the above methods as they didn't work for me. I did pow(64, 1/3.) along with pow(64, 1./3.) but the answer I got was 3
    Here's my logic.

    ans = pow(n, 1/3.);
    if (pow(ans, 3) != n){
       ans++;
    }
    
    0 讨论(0)
提交回复
热议问题