题目描述
代码如下
二分
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double x = sc.nextDouble();
double l = -10000;
double r = 10000;
while(r - l > 1e-8) {//精度比所求精度高 2位
double mid = (l + r)/2;
if(mid * mid * mid >= x) r = mid;
else l = mid;
}
//System.out.println(String.format("%.6f", l));
System.out.printf("%.6f", l); //保留 6位小数
}
}
幂次
需要注意的是:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double f = sc.nextDouble();
if(f < 0) {
f = Math.abs(f);
System.out.printf("-%.6f", Math.pow(f, 1.0/3));
}else {
System.out.printf("%.6f", Math.pow(f, 1.0/3));
}
}
}
开立方
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double f = sc.nextDouble();
System.out.printf("%.6f", Math.cbrt(f));
}
}