题解 | #求解立方根#
求解立方根
https://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca
二分法
由于参数是在实数范围内,所以需要注意的两个点:
- double的相等判断 (1f - 0.9f == 0.9f - 0.8f)的值是false
- 二分查找的边界
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); binarySearch(in.nextDouble()); } static void binarySearch(double d) { double l, r; if (1f < d) { l = 1f; r = d; } else if (0f < d && d < 1f) { l = d; r = 1f; } else if (-1 < d && d < 0) { l = -1f; r = d; } else { l = d; r = -1f; } // 上面这个表达式可以写成这样 但是会搜索一些没必要的区域 // double l = Math.min(-1, d); // double r = Math.max(1, d); while (true) { double mid = 0.5 * r + 0.5 * l; double c = cube(mid); if (equals(c, d)) { System.out.printf("%.1f", mid); break; } else if (c > d) { r = mid; } else { l = mid; } } } static boolean equals(double a, double b) { return Math.abs(a - b) < 1E-2; } static double cube(double d) { return d * d * d; } }#华为笔试#