题解 | #求解立方根#
求解立方根
http://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
while(in.hasNextDouble()){
double num = in.nextDouble();
double res = lfg(Math.abs(num));
System.out.println(num<0?"-"+res:res);
}
}
public static double lfg(double n){
if(n == 1||n == 0) return n;
double l = n>1?0:n;
double r = n>1?n:1;
double t = 0;
double p = n;
while(true){
t = (l+r)/2;
if(t == p) break;
if(Math.pow(t, 3) > n){
r = t;
} else {
l = t;
}
p = t;
}
return (double)Math.round(t*10)/10;
}
}
public class Main{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
while(in.hasNextDouble()){
double num = in.nextDouble();
double res = lfg(Math.abs(num));
System.out.println(num<0?"-"+res:res);
}
}
public static double lfg(double n){
if(n == 1||n == 0) return n;
double l = n>1?0:n;
double r = n>1?n:1;
double t = 0;
double p = n;
while(true){
t = (l+r)/2;
if(t == p) break;
if(Math.pow(t, 3) > n){
r = t;
} else {
l = t;
}
p = t;
}
return (double)Math.round(t*10)/10;
}
}