题解 | #求解立方根#
求解立方根
https://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main {
private static double split(double left, double right, double num) { double mid = (left + right) / 2; double res = 0.0; double value = mid * mid * mid; if (Math.abs(num - value) <= 0.001) { res = mid; } else if (value > num) { res = split(left, mid, num); } else if (value < num) { res = split(mid, right, num); } return res; } public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextDouble()) { // 注意 while 处理多个 case double num = in.nextDouble(); double anum = num; if (num < 0) { anum = 0 - anum; } double left = 0; double right = anum/2+1; double res = split(left, right, anum); if (num < 0) { System.out.print("-" + String.format("%.1f", res)); }else{ System.out.print(String.format("%.1f", res)); } } }
}