import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class 数的三次方根 {
public static double binarySearch(double x ){
double l = -10000;
double r = 10000;
// 如果保留6位就用1e-8,如果4位就用1e-4
while ((r - l) > 1e-8){
double mid = (l + r)/2;
if (mid * mid * mid >= x){
r = mid;
}else {
l = mid;
}
}
return l;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
double x = Double.parseDouble(br.readLine());
x = binarySearch(x);
// 由于java中的double没有自带固定小数点后位的函数,所以这里用格式化,通过转字符串,然后通过BigDecimal来处理,也可以用小数点分割,然后后面取出来6位和前面拼接,不过要单独处理进位,四舍五入还是上下取数都得自己定义,不如用函数
BigDecimal bd = new BigDecimal(Double.toString(x));
bd = bd.setScale(6, RoundingMode.HALF_UP);
System.out.println(bd);
}
}
标签:bd,java,BigDecimal,double,mid,方根,三次,import From: https://www.cnblogs.com/YaoMa/p/18010037