二分查找
注意浮点数如果为负数的情况,因为负数也可以开立方根
public static double cubeRoot(double num) {
double left = 0;
double right = num;
if (num < 0) {
left = num;
right = 0;
}
double mid = (left + right) / 2;
double ans = mid* mid *mid;
while (Math.abs(num - (ans)) > 1e-5) {
mid = (left + right) / 2;
ans = mid * mid * mid;
if (ans - num > 1e-5) {
right = mid;
} else if (num - ans > 1e-5){
left = mid;
}
}
return mid;
}