public class Solution { public double mySqrt(double n, double accuracy) { double mid = n/2.0; double left = 0.0; double right = n; double temp; while (left<right) { temp=(mid-n/mid)*mid; // 这里是防止int越界,相当于mid^2-n if (temp >0 && temp<accuracy) { return mid; }else if(mid > n/mid){ right = mid; }else{ left = mid; } mid = (left+right)/2.0; } return -1d; } public static void main(String[] args) { Solution solution = new Solution(); System.out.println(solution.mySqrt(2, 1e-2)); } }