题解 | #求解立方根#
求解立方根
https://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); double max = 100; double n = sc.nextDouble(); boolean negative = false; if (n < 0) { n = -n; negative = true; } int flag; double tar = 0; if (n <= 1) { for (double i = 0.1; i <= 1; i += 0.1) { double res = i * i * i; double distance = n - res; distance = distance > 0 ? distance : -distance; if (distance < max) { max = distance; tar = i; } } } else { for (double i = 0.1; i < n; i += 0.1) { double res = i * i * i; double distance = n - res; distance = distance > 0 ? distance : -distance; if (distance < max) { max = distance; tar = i; flag = 1; } else { flag = 0; } if (flag == 0) { break; } } } if (negative) { System.out.printf("%.1f\n", -tar); } else { System.out.printf("%.1f\n", tar); } } }