Java: квадратный корень из числа несколько раз, используя метод Ньютона
У меня есть задание, которое требует, чтобы я извлекал квадратный корень из числа столько раз, сколько захочу. Консоль запрашивает число, которое я хочу извлечь из квадратного корня, и сколько раз я хочу это сделать. Мой код извлекает квадратные корни из числа несколько раз, но он дает одно и то же значение. Как сделать так, чтобы значение приблизилось к квадратному корню числа?
import java.util.*;
public class SquareRootCalculator {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x; // the number whose root we wish to find
int n; // the number of times to improve the guess
// Read the values from the user.
System.out.print("input a positive integer (x): ");
x = scan.nextInt();
System.out.print("number of times to improve the estimate: ");
n = scan.nextInt();
int calculation = ((x/2) + (x/(x/2)) / 2);
for(int i = 0; i < n; i++) {
System.out.println((double)calculation);
}
/*
* The lines above read the necessary values from the user
* and store them in the variables declared above.
* Fill in the rest of the program below, using those
* variables to compute and print the values mentioned
* in the assignment.
*/
}
}
2 ответов:
Вместо
int calculation = ((x/2) + (x/(x/2)) / 2); for(int i = 0; i < n; i++) { System.out.println((double)calculation); }Использовать
for(int i = 0; i < n; i++) { x = ((x/2) + (x/(x/2)) / 2); System.out.println((double) x ); }
Измените его следующим образом:
double calculation = x; for(int i = 0; i < n; i++) { calculation = ((calculation/2) + (calculation/(calculation/2)) / 2) System.out.println(calculation); }
Comments