题解 | #求解立方根#

求解立方根

http://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca

二分查找法

#include <algorithm>
#include <cmath>
#include <iomanip>

using namespace std;

int main() {
    double x;
    while(cin>>x){
        double out;
       double left,right;
        if(x>=0&&x<1) {
            left = x;
            right = 1.0;
        }
        else if(x<0&&(x>-1)){
            right = x;
            left = -1.0;
        }
        else if (x>=1){
            left = 1.0;
            right = x;
        }
        else if (x<=1){
            left = x;
            right = -1.0;
        }
        while((right-left)>0.01){
            out = (right+left)/2;
            if(out*out*out>x) right =out;
            else left = out;
            
        }
        
        cout<<fixed<<setprecision(1)<<out<<endl;
    }
}
全部评论

相关推荐

投递字节跳动等公司10个岗位
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务