1 import java.util.Scanner; 2 3 public class Solution 4 { 5 public static void main(String[] args) 6 { 7 Scanner input = new Scanner(System.in); 8 System.out.print("Enter a number to calculate the sqrt: "); 9 double number = input.nextDouble(); 10 11 input.close(); 12 13 System.out.println("The sqrt is " + sqrt(number)); 14 } 15 16 public static double sqrt(double number) 17 { 18 double lastGuess = 1; 19 double nextGuess = (lastGuess + (number / lastGuess)) / 2; 20 21 while(Math.abs(nextGuess - lastGuess) > 0.0001) 22 { 23 lastGuess = nextGuess; 24 nextGuess = (lastGuess + (number / lastGuess)) / 2; 25 } 26 27 return nextGuess; 28 } 29 }
时间: 2024-10-15 06:51:32