题解 | #求解立方根#
求解立方根
https://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca
import java.util.Scanner; /** 二分查找法,不停的查找,知道差值< 0.000.1 即算为相等 这里只考虑非负数的情况,负数可以直接乘以-1得到 */ public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNext()) { // 注意 while 处理多个 case String s = in.nextLine(); double num = Double.valueOf(s); boolean flag = true; if(num < 0){ flag = false; num = -1 * num; } double result = 0; double i = 0; double j = num < 1 ? 1 : num; double mid = 0; while(i + 0.1 < j){ mid = i + (j-i)/2; double temp = mid * mid * mid; if(temp < num){ i = mid; }else { j = mid; } } if(num - i*i*i <= j*j*j - num){ result = i; }else{ result = j; } System.out.println(String.format("%.1f",(flag ? result : -1 * result))); } } }