题解 | #求解立方根#
求解立方根
https://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.hasNext()) { double num = in.nextDouble(); System.out.println(binarySearch(num)); } } public static double binarySearch(double num) { int isMinus = num<0?-1:1; num = Math.abs(num); double left = 0, right = num<1?1:num; while (right-left>0.1) { double med = (left + right) / 2; double x = Math.pow(med, 3); if (x == num) { return isMinus*(double)Math.round(med*10)/10; } else if(x>num){ right = med; } else if(x<num){ left = med; } //System.out.println(med); } double x1 = Math.pow(left, 3), x2=Math.pow(right, 3); if(Math.abs(x1-num) < Math.abs(x2-num)){ return isMinus*(double) Math.round(left*10)/10; } else{ return isMinus*(double) Math.round(right*10)/10; } } }