Java:使用Newton';s法

Java:使用Newton';s法,java,Java,我有一个任务,要求我将一个数字的平方根乘以我想要的次数。控制台询问我想要平方根的数字以及我想要平方根的次数。我的代码将数字平方根乘以几次,但给出的值相同。如何使值更接近数字的平方根 import java.util.*; public class SquareRootCalculator { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int x;

我有一个任务,要求我将一个数字的平方根乘以我想要的次数。控制台询问我想要平方根的数字以及我想要平方根的次数。我的代码将数字平方根乘以几次,但给出的值相同。如何使值更接近数字的平方根

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.
     */

    }
}
import java.util.*;
公共类平方计算器{
公共静态void main(字符串[]args){
扫描仪扫描=新扫描仪(System.in);
int x;//要查找其根的数字
int n;//改进猜测的次数
//从用户处读取值。
系统输出打印(“输入正整数(x):”;
x=scan.nextInt();
System.out.print(“改进估计的次数:”);
n=scan.nextInt();
int计算=((x/2)+(x/(x/2))/2);
对于(int i=0;i
将其更改为:

double calculation = x;

for(int i = 0; i < n; i++) {
    calculation = ((calculation/2) + (calculation/(calculation/2)) / 2)
    System.out.println(calculation);
}
双重计算=x;
对于(int i=0;i
而不是

int calculation = ((x/2) + (x/(x/2)) / 2);

for(int i = 0; i < n; i++) {
    System.out.println((double)calculation);
}
int计算=((x/2)+(x/(x/2))/2);
对于(int i=0;i
使用

for(int i=0;i
计算值在循环外部计算。所以它永远不会改变。你需要把它放在循环中,但是在循环之前声明它,这样它就不会每次都被覆盖。如果你想计算多次,你必须在循环中多次运行代码。现在您只需反复打印相同的值(计算)。因此,您要么编写一个反复调用的函数calculation(),要么将其放入循环中。请注意,在得到正确的平方根估计值之前,该公式必须重复多次。换句话说,当前循环所做的就是反复打印计算值。没有重复发生的逻辑或计算-它不是多次计算平方根。就是这样。非常感谢。
for(int i = 0; i < n; i++) {
    x = ((x/2) + (x/(x/2)) / 2);
    System.out.println((double) x );
}