模板
public class BinarySearch {
// 检查x是否满足某种性质
public static boolean check(double x) {
// 实现具体的检查逻辑
return false; // 这里仅为示例,实际根据需求修改
}
public static double bsearch_3(double l, double r) {
final double eps = 1e-6; // 精度要求
while (r - l > eps) {
double mid = (l + r) / 2;
if (check(mid)) {
r = mid;
} else {
l = mid;
}
}
return l;
}
public static void main(String[] args) {
double result = bsearch_3(0, 100); // 示例调用
System.out.println("结果: " + result);
}
}
例题:求数的平方根
package base;
import java.util.Scanner;
public class Sqrt_demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//求x的平方根
double x = sc.nextDouble();
sqrt(x);
}
public static void sqrt(double x){
double l =0,r = x;
while (r-l>1e-8){
double mid = (l+r)/2;
if (mid*mid>x) r=mid;
else l = mid;
}
System.out.println(String.format("%.6f",l));
}
}