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. 测试结果

开方算法的设计与实现

相关文章:

  • 2022-03-04
  • 2021-10-28
  • 2021-06-03
  • 2021-06-07
  • 2021-05-11
  • 2022-12-23
  • 2021-12-31
  • 2021-04-13
猜你喜欢
  • 2021-08-11
  • 2021-12-26
  • 2021-07-19
  • 2021-05-29
  • 2021-08-16
  • 2021-11-06
  • 2022-01-01
相关资源
相似解决方案