题解 | #求解立方根#
求解立方根
http://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
double n = sc.nextDouble();
double num = n>0?n:-n;//负数先当正数处理
double bottom=0;
double top =0;
//先假设 这个数的立方根是介于 bottom和top之间
while(top*top*top< num){
top++;
}
bottom=top-1;
//定义 bottom和top的中间值
double mid = bottom+(top-bottom)/2;
double mul = mid*mid*mid;
while(top-bottom>0.1){
//二分 逐渐判断top到mid 还是 mid到bottom
if(mul>num){
top=mid;
}else{
bottom=mid;
}
mid = bottom+(top-bottom)/2;
mul = mid*mid*mid;
}
if(n<0){
mid=-mid;
}
System.out.println(String.format("%.1f",mid));
}
}
}