我有一项任务,要求我根据需要将数字平方根。控制台询问我想要平方根的数字和我想要它的次数。我的代码平方根数倍,但它给出了相同的值。如何使值更接近数字的平方根?
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.
*/
}
}
答案 0 :(得分:2)
将其更改为:
double calculation = x;
for(int i = 0; i < n; i++) {
calculation = ((calculation/2) + (calculation/(calculation/2)) / 2)
System.out.println(calculation);
}
答案 1 :(得分: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 );
}