题解 | #求解立方根#
求解立方根
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
float a = (float)in.nextDouble();
System.out.println(f(a));
}
}
public static String f(float a) {
int i;
for (i = 3; i >= -3; i--) {
if (i * i * i <= a) {
//System.out.println(i);
break;
} else {
continue;
}
}
float fNum = i;
while (true) {
//System.out.println(fNum);
if (fNum * fNum * fNum == a) {
return String.format("%.1f",fNum);
} else if (fNum * fNum * fNum > a) {
return (fNum - 0.05f) * (fNum - 0.05f) * (fNum - 0.05f) <= a ? String.format("%.1f",fNum) :
String.format("%.1f",fNum-0.1f);
} else {
fNum += 0.1f;
}
}
}
}
查看11道真题和解析