finding cube root in C++?

后端 未结 12 640
自闭症患者
自闭症患者 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:57

    C++11 has the cbrt function (see for example http://en.cppreference.com/w/cpp/numeric/math/cbrt) so you can write something like

    #include 
    #include 
    
    int main(int argc, char* argv[])
    {
       const double arg = 20.0*(-3.2) + 30.0;
       std::cout << cbrt(arg) << "\n";
       std::cout << cbrt(-arg) << "\n";
       return 0;
    }
    

    I do not have access to the C++ standard so I do not know how the negative argument is handled... a test on ideone http://ideone.com/bFlXYs seems to confirm that C++ (gcc-4.8.1) extends the cube root with this rule cbrt(x)=-cbrt(-x) when x<0; for this extension you can see http://mathworld.wolfram.com/CubeRoot.html

提交回复
热议问题