题解 | #求解立方根#,二分法容易理解,效率也还可以,实现起来简单
求解立方根
http://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextDouble()) { // 注意 while 处理多个 case
double x = in.nextDouble();
double a = 1;
if (x < 0){
x *= -1;
a = -1;
}
double cubeRoot = getCubeRoot1(x) * a;
System.out.println(Double.parseDouble(String.format("%.1f", cubeRoot)));
}
}
// 只处理正数和0的立方根
public static double getCubeRoot1(double input) {
if (input == 1 || input == 0) {
return input;
}
double min = 0;
double max = input;
if (input < 1){
min = input;
max = 1;
}
// 精度要求
while ((max - min) > 0.001 ) {
double mid = (max + min) / 2;
if (mid * mid * mid > input) {
if (input > 0){
max = mid;
}
continue;
}
if (mid * mid * mid < input) {
min = mid;
continue;
}
return mid;
}
//这种情况是:在满足精确度的条件下无精确值,选择max作为近似值来返回。
//同样也可以选择min作为近似值来返回
return max;
}
}