题解 | #求解立方根#
求解立方根
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.hasNextDouble()) { // 注意 while 处理多个 case double a = in.nextDouble(); double b = calculateCubeRoot(a); System.out.println(b); } } public static double calculateCubeRoot(double number) { boolean isFuShu = false; if (number < 0) { isFuShu = true; number = -1 * number; } double epsilon = 0.00001; // 精度,可以调整以满足需求 double x = number; // 初始估计值 while (Math.abs(x * x * x - number) >= epsilon) { x = (2 * x + number / (x * x)) / 3; } double result = Math.round(x * 10.0) / 10.0; // 保留一位小数 if(isFuShu) { result = (-1) * result; } return result; } }