我试了一个int的,double实在不会。int可以用夹逼定律,代码如下:- package com.heima.practise;
- public class HalfTest {
- public static void main(String[] args) {
- int d = 26;
- int min = 1;
- int max = d;
- try {
- System.out.println(sqrt1(min,max,d));
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- private static int sqrt1(int min,int max,int num) throws Exception {
-
- int d = num;
- int mid = (min + max)/2;
- int mid2 = mid * mid;
- if(mid2>num)
- max = mid;
- else if(mid2<num)
- min = mid;
- else
- return mid;
- if(min>=max-1){
- throw new Exception("此数没有平方根!");
- }
- return sqrt1(min,max,d);
-
- }
- }
复制代码 |