题解 | #求解立方根#
求解立方根
https://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca
import java.util.Scanner;
import java.util.concurrent.atomic.DoubleAdder;
import java.math.BigDecimal;
import java.math.RoundingMode;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double sysValue = in.nextDouble();
BigDecimal sysDouble = new BigDecimal(sysValue).abs();
double value = sysDouble.doubleValue();
DoubleAdder atomicDouble = new DoubleAdder();
test(value, atomicDouble, value);
double resultValue = atomicDouble.doubleValue();
BigDecimal resultBi = BigDecimal.valueOf(resultValue).setScale(1,
RoundingMode.HALF_EVEN);
BigDecimal va = new BigDecimal("0.1");
BigDecimal multiply;
do {
resultBi = resultBi.add(va);
multiply = resultBi.multiply(resultBi).multiply(resultBi);
} while (multiply.doubleValue() < value);
BigDecimal subtractResult = resultBi.subtract(va);
BigDecimal abs = multiply.subtract(sysDouble).abs();
BigDecimal abs1 = subtractResult.multiply(subtractResult).multiply(
subtractResult).subtract(sysDouble).abs();
if (abs.compareTo(abs1) < 0) {
test2(sysValue, resultBi);
} else {
test2(sysValue, subtractResult);
}
}
private static void test(Double sysChangeValue, DoubleAdder atomicDouble,
double sysValue) {
if (sysChangeValue * sysChangeValue * sysChangeValue < sysValue) {
atomicDouble.add(sysChangeValue);
return;
} else {
sysChangeValue = sysChangeValue / 2;
test(sysChangeValue, atomicDouble, sysValue);
}
}
private static void test2(double sysValue, BigDecimal v) {
if (sysValue > 0) {
System.out.println(v);
} else {
System.out.println("-" + v);
}
}
}