题解 | #求解立方根#
求解立方根
http://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca
import java.util.*; public class Main { static double i=0.0; public static void main( String [] agrs){ Scanner sc = new Scanner(System.in); double input= sc.nextDouble(); getResult(input,20.0,-20);
System.out.print((double)Math.round(i*10)/10);
}
//迭代函数
public static void getResult(double input, double max, double min) {
if (input>0) {
i = (max + min) / 2;
double s=i*i*i;
//精度控制在0.01级别
if ((s- input <= 0.01 && s - input >= 0) ) {
return;
}
if (s - input > 0.01 ) {
getResult(input, i, min);
} else {
getResult(input, max, i);
}
} else {
i = (min + max) / 2;
double s=i*i*i;
if ((input-s <= 0.01 && input-s >= 0) ) {
return;
}
if (input-s > 0.01 ) {
getResult(input, max, i);
} else {
getResult(input, i, min);
}
}
}
}