finding cube root in C++?

后端 未结 12 621
自闭症患者
自闭症患者 2020-12-03 15:18

Strange things happen when i try to find the cube root of a number.

The following code returns me undefined. In cmd : -1.#IND

cout<

        
12条回答
  •  情深已故
    2020-12-03 15:40

    I was looking for cubit root and found this thread and it occurs to me that the following code might work:

    #include 
    using namespace std;
    
    function double nth-root(double x, double n){
        if (!(n%2) || x<0){
            throw FAILEXCEPTION(); // even root from negative is fail
        }
    
        bool sign = (x >= 0);
    
        x = exp(log(abs(x))/n);
    
        return sign ? x : -x;
    }
    

提交回复
热议问题