Implementdouble sqrt(double x)andx >= 0

Solution: 注意x < 1时,要把j设为1

eg: 0.01 ->0.1

    public double sqrt(double x) {
        if(x <= 0){
            return x;
        }
        double i = 0, j = x;
        if(x < 1){
            j = 1;
        }
        while(j - i > 0.0000000001){
            double mid = (i + j) / 2;
            if(mid * mid > x){
                j = mid;
            } else{
                i = mid;
            }
        }
        if(j * j <= x){

            return j;
        }
        return i;
    }

.

results matching ""

    No results matching ""