开方算法的设计与实现

1. 算法原理

使用二分法对开方进行运算。

2. 算法描述

采用small进行标记开方结果所在区域的最小值,采用bigger进行标记开方结果所在区域的最大值,运用二分法对开方结果所在区域,进行缩小(逼近),再运用while循环实现对开方结果精确度进行控制;最后再主函数中用scanner方法从键盘上输入被开方数x,即可求解;

3. 算法实现

import java.util.Scanner;

public class open {

public static void main(String[] args) {

    Scanner scanner=new Scanner(System.in);

    double x=scanner.nextInt();

System.out.print(sqrt(x));

}

public static double sqrt(double x) {

double small= 0;

double biggerx;

double mid = (small + bigger) / 2;

while(Math.abs(mid*mid-x)>=0.01) {

if(mid * mid < x) {

small=mid;

mid=(mid + bigger)/2;

}

else{

bigger=mid;

mid=(mid+small)/2;

}

return mid;

}

}

 

4. 测试结果

开方算法的设计与实现