1 import java.util.Scanner; 2 3 public class sqrtNewton { 4 public static void main(String[] args) { 5 System.out.println("请输入要开方的数:"); 6 Scanner input = new Scanner(System.in); 7 double num = input.nextDouble(); 8 double e = 0.01F; 9 sqrt(num, e); 10 num = 2; 11 e = 0.0001F; 12 sqrt(num, e); 13 num = 2; 14 e = 0.00001F; 15 sqrt(num, e); 16 } 17 private static double sqrt(double num, double e) { 18 double gssn = num / 2; 19 double e0; 20 int cnt = 0; 21 do { 22 gssn= (gssn + num / gssn) / 2; 23 e0 = gssn*gssn - num; 24 cnt++; 25 System.out.printf("尝试 %f, 误差: %f\n", gssn, e0); 26 } while (e0 > e); 27 28 System.out.printf("尝试 %d 次, 结果为: %f\n", cnt, gssn); 29 return gssn; 30 } 31 }