题解 | #求解立方根#
求解立方根
https://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca
import java.util.Scanner; import java.text.DecimalFormat; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (sc.hasNext()) { // 注意 while 处理多个 case Double d = sc.nextDouble(); System.out.printf("%.1f",getResult(d)); } } private static double getResult(double b) { boolean flag = true; if(b<0){ b = - b; flag = false; } double mid =0.0,left=0.0,right=b; //当b小于1的时候,立方根比b大,但是比1小 right = Math.max(b,1); while(right-left>0.01){ mid = right - (right-left)/2; if(mid*mid*mid>b){ right = mid; }else{ left = mid; } } if(!flag){ mid = -mid; } return mid; } }