题解 | #求解立方根#
求解立方根
https://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
// 找规律。分为ads在0-1和abs 1-21两种情况处理
public class Main {
public static void main(String[] args) {
cube();
}
private static void cube() {
Scanner in = new Scanner(System.in);
double aDouble = in.nextDouble();
if (aDouble != 0 && aDouble >= -21 && aDouble <= 21) {
if (-1 == aDouble || 1 == aDouble) {
System.out.println(aDouble);
}
double de_c = 0;
double de = 0;
double abs = Math.abs(aDouble);
if ((0 < abs && abs < 1)) {
for (double i = 0.10; i < 1; i = i + 0.10) {
double d = i * i * i;
double v = Math.abs(abs - d);
if (i == 0.1) {
de_c = v;
de = i;
} else if (de_c > v) {
de_c = v;
de = i;
}
}
String format = String.format("%.1f", de);
if (aDouble > 0) {
System.out.println(format);
} else {
System.out.println("-" + format);
}
} else {
int intValue = 0;
int intValueSmall = 0;
boolean f = true;
for (int i = 2; i <= 21; i++) {
int v = i * i * i;
if (v > abs && f) {
intValue = i;
intValueSmall = i - 1;
for (double a = intValueSmall; a < intValue; a = a + 0.1) {
double d = a * a * a;
double vx = Math.abs(abs - d);
if (a == intValueSmall) {
de_c = vx;
de = a;
} else if (de_c > vx) {
de_c = vx;
de = a;
}
}
f = false;
}
}
String format = String.format("%.1f", de);
if (aDouble > 0) {
System.out.println(format);
} else {
System.out.println("-" + format);
}
}
}
// 库函数
//Math.cbrt(in.nextDouble());
}
}

