题解 | #求解立方根#
求解立方根
http://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca
跟大佬混出来的二分法解法,牛顿啥的,我好像已经过了学数学的年纪了,看不懂。。。
不过决定道理都差不多,尤其是说明了小数范围的情况下
特别注意,当输入num小于一的时候,记得右边界必须设定为1才行
public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String i = sc.nextLine(); double num = Double.parseDouble(i); boolean f= num<0; if(f) num*=-1; double pow = pow(num); DecimalFormat df = new DecimalFormat("######0.0"); if(f){ System.out.println("-"+df.format(pow)); }else { System.out.println(df.format(pow)); } } } //二分法 static double pow(double num){ if ( num == 0) { return 0; } double left =0; double right = num>1?num:1; double mid = (right+left)/2; while (Math.abs(mid * mid * mid - num)>0.01&&left<=right){ if(mid * mid * mid>num){ right=mid-0.1; }else { left=mid+0.1; } mid = (right+left)/2; } return left; }